How to use the tube in the exec parameter for the find command?

I am trying to build a find command to process a bunch of files in a directory using two different executables. Unfortunately, -exec on find does not allow the use of pipe or even \| , because the shell first interprets this character.

Here is specifically what I am trying to do (which does not work because pipe completes the find command):

 find /path/to/jpgs -type f -exec jhead -v {} | grep 123 \; -print 
+55
bash shell find
Sep 15 '08 at 9:45
source share
5 answers

try it

 find /path/to/jpgs -type f -exec sh -c 'jhead -v {} | grep 123' \; -print 

Alternatively, you can try to embed the exec statement in the sh script, and then run:

 find -exec some_script {} \; 
+55
Sep 15 '08 at 9:54
source share

A slightly different approach is to use xargs:

 find /path/to/jpgs -type f -print0 | xargs -0 jhead -v | grep 123 

which was always a little easier for me to understand and adapt (the arguments -print0 and -0 are needed to deal with file names containing spaces)

This may be (not verified) more efficient than using -exec, because it will transfer the list of files to xargs, and xargs ensures that the jhead command is not too long.

+11
Sep 15 '08 at 10:52
source share

With -exec you can only run one executable file with some arguments, and not with arbitrary shell commands. To get around this, you can use sh -c '<shell command>' .

Note that using -exec pretty inefficient. For each file found, the command must be executed again. It would be more effective if you could avoid this. (For example, moving grep outside of -exec or passing the results from find to xargs , as suggested by Palmin .)

+3
Sep 15 '08 at 9:56
source share

Using the find for this type of task may not be the best alternative. I often use the following command to search for files containing the requested information:

 for i in dist/*.jar; do echo ">> $i"; jar -tf "$i" | grep BeanException; done 
+3
Feb 27 '11 at 3:29
source share

Since this lists, you should not:

 find /path/to/jpgs -type f -exec jhead -v {} \; | grep 123 

or

 find /path/to/jpgs -type f -print -exec jhead -v {} \; | grep 123 

Put your grep on the -exec search results.

+1
Sep 15 '08 at 9:52
source share



All Articles