删除包含string1和string2的所有文件

时间:2014-06-25 12:29:26

标签: shell grep

以下脚本查找并打印包含string1或string2的所有文件的名称。

但是,我无法弄清楚如何更改此代码,以便它只打印包含string1和string2的文件。请建议所需的更改

   number=0
   for file in `find -name "*.txt"`
   do
       if [ "`grep "string2\|string1" $file`" != "" ]   // change has to be done here
       then

      echo "`basename $file`"
      number=$((number + 1))
       fi
   done
   echo "$number"

2 个答案:

答案 0 :(得分:2)

使用grep和cut:

grep -H string1 input | grep -E '[^:]*:.*string2' | cut -d: -f1

您可以使用find命令:

find -name '*.txt' -exec grep -H string1 {} \; | grep -E '[^:]*:.*string2'

如果模式不一定在同一条线上:

find -name '*.txt' -exec grep -l string1 {} \; | \
            xargs -n 1 -I{} grep -l string2 {}

答案 1 :(得分:0)

此解决方案可以处理名称中包含空格的文件:

number=0
oldIFS=$IFS
IFS=$'\n'
for file in `find -name "*.txt"`
do
  if grep -l "string1" "$file" >/dev/null; then
    if grep -l "string2" "$file" >/dev/null; then
       basename "$file"
      number=$((number + 1))
    fi
  fi
done
echo $number
IFS=$oldIFS