如何在grep中排除符号链接?

时间:2014-02-12 20:11:02

标签: grep

我想grep -R一个目录但排除符号链接我该怎么办?

可能像grep -R --no-symlinks之类的东西?

谢谢。

4 个答案:

答案 0 :(得分:54)

如果在命令行中未指定-r v2.11-8 and on调用Gnu grep excludes symlinks,则在使用-R调用时包含它们。

答案 1 :(得分:14)

如果您已经知道要排除的符号链接的名称:

grep -r --exclude-dir=LINK1 --exclude-dir=LINK2 PATTERN .

如果符号链接的名称不同,可以先用find命令排除符号链接,然后grep输出的文件:

find . -type f -a -exec grep -H PATTERN '{}' \;

' -H' to grep将文件名添加到输出中(如果grep以递归方式搜索,则这是默认值,但不在此处,grep将被传递给单个文件名。)

我通常想修改grep以排除源控制目录。初始查找命令最有效地完成了这项工作:

find . -name .git -prune -o -type f -a -exec grep -H PATTERN '{}' \;

答案 2 :(得分:5)

目前..以下是在使用grep时排除符号链接的方法


如果您只想要与搜索匹配的文件名:

for f in $(grep -Rl 'search' *); do if [ ! -h "$f" ]; then echo "$f"; fi; done;

解释:

  • grep -R # recursive
  • grep -l # file names only
  • if [ ! -h "file" ] # bash if not a symbolic link

如果您想要匹配的内容输出,那么双重grep:

srch="whatever"; for f in $(grep -Rl "$srch" *); do if [ ! -h "$f" ]; then
  echo -e "\n## $f";
  grep -n "$srch" "$f";
fi; done;

解释:

  • echo -e # enable interpretation of backslash escapes
  • grep -n # adds line numbers to output

..当然不完美。但它可以完成工作!

答案 3 :(得分:2)

如果你使用的是没有Aryeh Leib Taurog答案中描述的-r行为的旧grep,你可以使用findxargsgrep的组合:

find . -type f | xargs grep "text-to-search-for"
相关问题