Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a pipe in the exec parameter for a find command?

Tags:

find

bash

shell

I'm trying to construct a find command to process a bunch of files in a directory using two different executables. Unfortunately, -exec on find doesn't allow to use pipe or even \| because the shell interprets that character first.

Here is specifically what I'm trying to do (which doesn't work because pipe ends the find command):

find /path/to/jpgs -type f -exec jhead -v {} | grep 123 \; -print 
like image 815
hoyhoy Avatar asked Sep 15 '08 09:09

hoyhoy


People also ask

How do I use the pipe command in Linux?

You can make it do so by using the pipe character '|'. Pipe is used to combine two or more commands, and in this, the output of one command acts as input to another command, and this command's output may act as input to the next command and so on.

What is exec in find command?

Find exec causes find command to execute the given task once per file is matched. It will place the name of the file wherever we put the {} placeholder. It is mainly used to combine with other commands to execute certain tasks. For example: find exec grep can print files with certain content.

What is pipe used for in CMD?

The | command is called a pipe. It is used to pipe, or transfer, the standard output from the command on its left into the standard input of the command on its right.


2 Answers

Try this

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

Alternatively you could try to embed your exec statement inside a sh script and then do:

find -exec some_script {} \; 
like image 136
Martin Marconcini Avatar answered Oct 15 '22 05:10

Martin Marconcini


A slightly different approach would be to use xargs:

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

which I always found a bit easier to understand and to adapt (the -print0 and -0 arguments are necessary to cope with filenames containing blanks)

This might (not tested) be more effective than using -exec because it will pipe the list of files to xargs and xargs makes sure that the jhead commandline does not get too long.

like image 29
Palmin Avatar answered Oct 15 '22 06:10

Palmin