2014-01-07 93 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 {} \;