How do you exclude symlinks in a grep?

后端 未结 4 873
梦如初夏
梦如初夏 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: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!

提交回复
热议问题