Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
718 views
in Technique[技术] by (71.8m points)

unix - How to use pipe within -exec in find

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/dir -type f -print -exec grep yourstring {} ;

I tried to put the pipelines there with "cat" and "head -1", but it didn't work very well. I tried to use parenthesis somehow, but I didn't manage to work out how exactly to put them there. I would be very thankful for your help. I know how to work it out other way, without using the find, but we tried to do it in school with the usage of find and pipeline, but couldn`t manage how to.

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

This is somehow how we tried to do it, but could't manage the parenthesis and wheter it is even possible. I tried to look through net, but couldn' t find any answers.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/' {} ;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...