Reputation: 1098
I would like to execute a command with the file names as parameter on all files in a directory with different file extensions. I tried this:
for i in *.jpg *.docx *.gdi;
do
mycommand dosth -i "$i" -o "${i%.*}.myext";
done
But if one of the file extensions does not exist in the folder I get an error saying "file not found". How do I have to change the script?
Upvotes: 0
Views: 565
Reputation: 532303
As Debian uses dash
, there is no option for ignoring unmatched patterns. You can distinguish between a match result and an unmatched pattern by checking if a file named $i
exists. If it does not, then it obviously was not the result of pathname expansion (which only produces existing files, race conditions aside.)
for i in *.jpg *.docx *.gdi
do
[ -e "$i" ] || continue # E.g., if $i == "*.jpg" after no JPG files were found
mycommand dosth -i "$i" -o "${i%.*}.myext"
done
In a Dockerfile, as the entire command has to be on one logical line, semicolons are necessary:
ENTRYPOINT for i in *.jpg *.docx *.gdi; do \
[ -e "$i" ] || continue; \
mycommand dosth -i "$i" -o "${i%.*}.myext"; \
done
Upvotes: 1
Reputation: 44254
I'd recommend using find to search for multiple extensions like so:
find . -type f \( -iname \*.jpg -o -iname \*.gdi -o -iname \*. docx \) -exec mycommand {} \;
The -exec
can be altered with some more parameters if needed.
How to run find -exec?
Based on the commends, a solution thats spawns a shell so we can use substitution:
find . -type f \( -iname \*.jpg -o -iname \*.gdi -o -iname \*. docx \) -exec sh -c 'mycommand dosth -i "$0" -o "${0%.*}.myext"; ' {} \;
How to substitute string in {} in "find (...) -exec (...) {} \;" bash command?
Upvotes: 1