How to use pipe within -exec in find

前端 未结 2 1051
感情败类
感情败类 2020-12-09 08:29

Is there any way to use pipe within an -exec in find? I don\'t want grep to go through whole file, but only through first line of each file.

find /path/to/di         


        
相关标签:
2条回答
  • 2020-12-09 09:07

    In order to be able to use a pipe, you need to execute a shell command, i.e. the command with the pipeline has to be a single command for -exec.

    find /path/to/dir -type f -print -exec sh -c "cat {} | head -1 | grep yourstring" \;
    

    Note that the above is a Useless Use of Cat, that could be written as:

    find /path/to/dir -type f -print -exec sh -c "head -1 {} | grep yourstring" \;
    

    Another way to achieve what you want would be to say:

    find /path/to/dir -type f -print -exec awk 'NR==1 && /yourstring/' {} \;
    
    0 讨论(0)
  • 2020-12-09 09:12

    This does not directly answer your question, but if you want to do some complex operations you might be better off scripting:

    for file in $(find /path/to/dir -type f); do echo ${file}; cat $file | head -1 | grep yourstring; done

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