带通配符的GREP,但排除特定术语并返回文件名

时间:2014-10-06 21:44:20

标签: regex string grep filenames

我是使用grep的新手,我需要执行相当复杂的查询,所以这里有:

我想以递归方式grep到字符串的目录:====\d+ 其中\ d +是一个或多个小数(perl语法),字符串不同于====0

我希望grep返回包含====\d+

的文件的文件名

3 个答案:

答案 0 :(得分:3)

要仅显示没有路径的文件名,您可以

grep -ERl '====[1-9]\d*' . | while read name; do basename $name; done

或者,如果您的文件名可以包含空格,换行符或其他陌生感,请使用

grep -ZERl '====[1-9]\d*' . | while IFS= read -r -d '' name; do 
    basename "$name"; 
done

使用的grep标志是(来自GNU grep的手册):

   -E, --extended-regexp
          Interpret  PATTERN  as  an extended regular expression (ERE, see
          below).  (-E is specified by POSIX.)
   -R, --dereference-recursive
          Read all files under each directory,  recursively.   Follow  all
          symbolic links, unlike -r.
   -l, --files-with-matches
          Suppress  normal  output;  instead  print the name of each input
          file from which output would normally have  been  printed.   The
          scanning  will  stop  on  the  first match.  (-l is specified by
          POSIX.)
   -Z, --null
          Output  a  zero  byte  (the  ASCII NUL character) instead of the
          character that normally follows a file name.  For example,  grep
          -lZ  outputs  a  zero  byte  after each file name instead of the
          usual newline.  This option makes the output  unambiguous,  even
          in the presence of file names containing unusual characters like
          newlines.  This option can  be  used  with  commands  like  find
          -print0,  perl  -0,  sort  -z, and xargs -0 to process arbitrary
          file names, even those that contain newline characters.

答案 1 :(得分:2)

随意尝试:

grep -rle "====[1-9][0-9]*" /path/to/directory

答案 2 :(得分:2)

试试这样:

grep -rle '====[1-9][0-9]*' /path/to/files

其中:

-r recurse into the directory (and sub-directories)
-l only list files
-e use regexp

正则表达式将匹配四个相等的符号,后跟一个大于零的数字,然后是零个或多个其他数字。