Alex
Alex

Reputation: 129

bash: find all files in a directory and use part of the name as argument for a command

I need to get all of the jpg files in a directory, and execute the following command on each one:

mycommand -in <imagebasename>.jpg -out <imagebasename>.tif --otherparam paramvalue

I thought about:

find . -name "*.jpg" -exec mycommand -in {} -out {}.tif --otherparam paramvalue\;

but this will pass something like "./<imagebasename>.jpg" to mycommand. I need to pass <imagebasename> only instead.

I don't need to process the directories recursively.

Upvotes: 1

Views: 1591

Answers (1)

devnull
devnull

Reputation: 123448

Try:

find . -name "*.jpg" -exec sh -c 'mycommand -in $0 -out "${0%.*}.tif" --otherparam paramvalue' {} \;

This will pass command of the form mycommand -in <imagebasename>.jpg -out <imagebasename>.tif --otherparam paramvalue to -exec.

EDIT: For removing leading ./, you could say:

find . -name "*.jpg" -exec bash -c 'f={}; f=${f/.\//}; echo mycommand -in "${f}" -out "${f%.*}.tif" --otherparam paramvalue' {} \;

(Note that the interpreter for -exec has changed.)

Upvotes: 3

Related Questions