2014-01-07 91 views
0
#!/bin/bash 

echo "Enter the search string" 
read str 

for i in `ls -ltr | grep $str > filter123.txt ; awk '{ print $9 }' filter123.txt` ; do 

if [ $i != "username_list.txt" || $i != "user_list.txt" ] ; then 

else 
rm $i 
fi 
done 

我是unix shell scritping的初學者,我使用grep方法基於給定的字符串創建刪除文件的上述文件。而我執行上面的腳本文件,它顯示錯誤,如「./rm_file.txt:第10行:語法錯誤附近的意外令牌」其他「。請提供此腳本中的錯誤信息。Unix如果條件錯誤內循環

+1

爲什麼你使用'grep'和'awk'和臨時文件?只要做'ls -ltr | awk「/ $ str/{print \ $ 9}」'(如果str包含某些字符,將會失敗,但grep $ str也會失敗) –

+0

使用'[[]]'(參見http://mywiki.wooledge。組織/ BashPitfalls#A.5B_.24foo_.3D_.22bar.22_.5D)。也不知道你爲什麼試着'如果!a || !b然後沒有別的東西'而不是在邏輯上等價的'如果一個&& b然後什麼''。 – BroSlow

回答

1
thenelse沒有什麼之間

,如果你想要做什麼,你可以把:

在名稱中帶有特定字符串現任所長刪除文件,你可以使用find

#!/bin/bash 
read -p "Enter the search string: " str 

# to exclude "username_list.txt" and "user_list.txt" 
find . -maxdepth 1 -type f -name "*$str*" -a -not \(-name "username_list.txt" -o -name "user_list.txt" \) | xargs -I'{}' ls {} 
+0

亞..現在它的工作.. –

1

要使用帶[的布爾運算符,您可以使用以下之一:

if [ "$i" != username_list.txt ] && [ "$i" != user_list.txt ] ; then ... 
if [ "$i" != username_list.txt -a "$i" != user_list.txt; then ... 

但在這種情況下,它可能是清潔劑使用的情況下statment:

case "$i" in 
username_list.txt|user_list.txt) : ;; 
*) rm "$i";; 
esac 
3

有幾個問題與您的代碼:

  1. Don't parse the output of ls。雖然它可能在很長時間內工作,但它會打破某些文件名,並且有更安全的選擇。

  2. 用另一根管替換filter123.txt

  3. 您可以否定條件的退出狀態,以便您不需要else子句。

  4. 您的if條件始終爲真,因爲任何文件名都將不等於兩個選項之一。您可能的意思是使用&&

  5. ||&&[ ... ]內部不可用。使用兩個[ ... ]命令或使用[[ ... ]]

解決以上項目:

for i in *$str*; do 
    if [[ $i != username_list.txt && $i = user_list.txt ]]; then 
     rm "$i" 
    fi 
done 
1

它也可以用做find

find . -maxdepth 1 -type f -name "*$str*" ! -name username_list.txt ! -name user_list.txt -exec rm {} \;