How do you exclude symlinks in a grep?

后端 未结 4 870
梦如初夏
梦如初夏 2020-12-30 18:36

I want to grep -R a directory but exclude symlinks how dow I do it?

Maybe something like grep -R --no-symlinks or something?

Thank

相关标签:
4条回答
  • 2020-12-30 19:08

    If you already know the name(s) of the symlinks you want to exclude:

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

    If the name(s) of the symlinks vary, maybe exclude symlinks with a find command first, and then grep the files that this outputs:

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

    The '-H' to grep adds the filename to the output (which is the default if grep is searching recursively, but is not here, where grep is being handed individual file names.)

    I commonly want to modify grep to exclude source control directories. That is most efficiently done by the initial find command:

    find . -name .git -prune -o -type f -a -exec grep -H PATTERN '{}' \;
    
    0 讨论(0)
  • 2020-12-30 19:09

    For now.. here is how I would exclude symbolic links when using grep


    If you want just file names matching your search:

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

    Explaination:

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

    If you want the matched content output, how about a double grep:

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

    Explaination:

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

    .. It's not perfect of course. But it could get the job done!

    0 讨论(0)
  • 2020-12-30 19:12

    If you're using an older grep that does not have the -r behavior described in Aryeh Leib Taurog's answer, you can use a combination of find, xargs and grep:

    find . -type f | xargs grep "text-to-search-for"
    
    0 讨论(0)
  • 2020-12-30 19:13

    Gnu grep v2.11-8 and on if invoked with -r excludes symlinks not specified on the command line and includes them when invoked with -R.

    0 讨论(0)
提交回复
热议问题