我想检查目录中的所有文件是否可以包含两次或更多次字符串。
检查单个" occurrence of a specific string using bash"看起来很简单:
if grep -q "LineString" "$File"; then
Some Actions # SomeString was found
fi
但如何算到两个?
答案 0 :(得分:1)
使用(( ))
进行数字比较:
if (( $(grep -c -- "LineString" "$file") >= 2 )); then
# your logic
fi
循环浏览所有文件:
#!/bin/bash
shopt -s nullglob # make glob expand to nothing if there are no matching files
for file in *; do
[[ -f $file ]] || continue
if (( $(grep -c -- "LineString" "$file") >= 2 )); then
# your logic
fi
done
如果您处理的是非常庞大的文件且grep
支持-m
选项,那么您可以使用grep -cm 2
优化读取:
#!/bin/bash
shopt -s nullglob
for file in *; do
[[ -f $file ]] || continue
if (( $(grep -cm 2 -- "LineString" "$file") >= 2 )); then
# your logic
fi
done
答案 1 :(得分:0)
试试这个
if [ `grep "LineString" $file | wc -l` -gt 1 ]; then
echo "done found";
' do something
fi;