Suppose I have a folder containing files with names like
file1.txt
file2.txt
file2.txt
etc. I would like to run a command on each of them, like so:
mycommand file1.txt -o file1-processed.txt
mycommand file2.txt -o file2-processed.txt
mycommand file3.txt -o file3-processed.txt
etc.
There are several similar questions on this site – the difference is that I want to insert the -processed
test into the middle of the file name, before the extension.
It seems like find
should be the tool for the job. If it wasn't for the -o
flag I could do
find *.txt -exec mycommand "{}" ";"
However, the {}
syntax gives the whole file name, e.g. file1.txt
etc., so I can't add the "-processed
" in between the filename and its extension. A similar problem exists with using a simple bash for
loop.
Is there a simple way to accomplish this task, using find
or otherwise?
Best Answer
If all the files to be processed are in the same folder, you don't need to use
find
, and can make do with native shell globbing.The shell idiom
${foo%bar}
removes the smallest suffix string matching the patternbar
from the value offoo
, in this case the.txt
extension, so we can replace it with the suffix you want.