'How do I glob and repeat command line argument with option repeated?
I want to run a command line program for multiple inputs like this
image_convert -I ./a.png -I ./b.png ...
The -I is mandatory before each file. Can I somehow do this for all png files in the directory using bash shell glob syntax, e.g., something like this
image_convert -I ./*.png
(this doesn't work)
Solution 1:[1]
image_convert -I ./*.png would expand to something like: image_convert -I ./a.png ./b.png.
You can use a loop and an array instead:
args=()
for arg in ./*.png
do
[ -f "$arg" ] || continue
args+=("-I" "$arg")
done
image_convert "${args[@]}"
If you want to deal with a POSIX shell, then you can utilize the array $@:
set -- # empty $@
for arg in ./*.png
do
[ -f "$arg" ] || continue
set -- "$@" -I "$arg" # Re-set $@ with '-I "$arg"' added for each iteration
done
image_convert "$@"
Solution 2:[2]
You could combine printf with xargs:
printf -- '-I\0%s\0' *.png | xargs -0 image_convert
Solution 3:[3]
I ended up using xargs from command line:
ls -1 ./*.png | xargs -d '\n' -n 1 image_convert -I
Solution 4:[4]
You can also use find command.
find . -type f -iname '*.png' -exec image_convert -I '{}' \+
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | hovnatan |
| Solution 4 | Darkman |
