2013-05-14 86 views
2

我在这里搜索过,但仍无法找到我的通配问题的答案。在bash脚本中防止通配符扩展

我们有文件“file.1”到“file.5”,如果我们的隔夜处理正常,每个文件都应该包含字符串“completed”。

我认为这是一件好事,首先检查是否有一些文件,然后我想grep他们看我是否找到5“完成”的字符串。下面无辜的方法是行不通的:

FILES="/mydir/file.*" 
if [ -f "$FILES" ]; then 
    COUNT=`grep completed $FILES` 
    if [ $COUNT -eq 5 ]; then 
     echo "found 5" 
else 
    echo "no files?" 
fi 

感谢您的任何意见....莱尔

+0

您的意思是'COUNT = \'grep的完成 '$文件' | wc -l \'' – 2013-05-14 00:11:26

+1

看起来真正的问题是如何计算文件,而不是如何防止通配符扩展。正确?你会反对改变主题(或让别人改变它)吗? – 2013-05-14 00:21:32

回答

3

http://mywiki.wooledge.org/BashFAQ/004,以计算文件的最好方法是使用一个数组(与nullglob选项) :

shopt -s nullglob 
files=(/mydir/files.*) 
count=${#files[@]} 

如果要收集这些文件的名称,你可以做到这一点,像这样(假设GNU的grep):

completed_files=() 
while IFS='' read -r -d '' filename; do 
    completed_files+=("$filename") 
done < <(grep -l -Z completed /dev/null files.*) 
((${#completed_files[@]} == 5)) && echo "Exactly 5 files completed" 

这种方法有些冗长,但保证即使使用非常不寻常的文件名也能正常工作。

0

你可以这样做是为了防止通配符:

echo \'$FILES\' 

但似乎你有一个不同的问题

2

试试这个:

[[ $(grep -l 'completed' /mydir/file.* | grep -c .) == 5 ]] || echo "Something is wrong" 

将打印“有些事情不对”,如果没有按找不到5 completed行。

更正缺少的 “-l” - 解释

$ grep -c completed file.* 
file.1:1 
file.2:1 
file.3:0 

$ grep -l completed file.* 
file.1 
file.2 

$ grep -l completed file.* | grep -c . 
2 

$ grep -l completed file.* | wc -l 
    2 
+1

'grep |有什么意义? grep -c',而不是一个'grep -c'? – 2013-05-14 00:27:23

+0

@CharlesDuffy查看编辑 – jm666 2013-05-14 00:39:03