Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use pipe within -exec in find

Tags:

find

unix

pipe

exec

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.

like image 665
beranpa8 Avatar asked Feb 17 '14 09:02

beranpa8


People also ask

How do you find the pipe command?

Now we know how the find statement works, let's explore the case where we want to use the find command along with a pipe. A pipe in Linux is just a vertical bar on your keyboard. It is used to consider the command that is on the left side of it as an input to the command on the right side of it.

Can you pipe into grep?

grep is very often used as a "filter" with other commands. It allows you to filter out useless information from the output of commands. To use grep as a filter, you must pipe the output of the command through grep . The symbol for pipe is " | ".

How do I search for a word inside a file in Linux?

Grep is a Linux / Unix command-line tool used to search for a string of characters in a specified file. The text search pattern is called a regular expression. When it finds a match, it prints the line with the result. The grep command is handy when searching through large log files.


2 Answers

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/' {} \; 
like image 109
devnull Avatar answered Sep 26 '22 10:09

devnull


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

like image 33
crutux Avatar answered Sep 24 '22 10:09

crutux