Following command outputs a list of file names:
find ./ -type f -name "*.yaml"
I want to change the output so that it returns a single string:
-f /path/to/file-1.yaml -f /path/to/file-2.yaml ...
I tinkered with sed, tr and awk without success. How can this be achieved?
If you want to make a single string, I would:
find ./ -type f -name "*.yaml" -printf "-f %p " | sed 's/ $//'
The sed
is just needed to remove last trailing space.
Not recommended: If your paths do not contain newlines, spaces, tabs, *
, ?
or [
and your IFS
variable is default, you might risk it and just forward the above command as arguments to another command and depend on word splitting expansion to split the result on multiple strings. Otherwise, filename expansion or word splitting expansion will split it in wrong places.
Recommended: If you want to generate command line options -f <file>
and store them in a bash array for later use, in Bash I would:
readarray -d '' arr < <(find ./ -type f -name "*.yaml" -print0)
args=()
for i in "${arr[@]}"; do
args+=("-f" "$i")
done
cmd "${args[@]}"
Much simpler is to glue -f
to the filenames:
readarray -d '' arr < <(find ./ -type f -name "*.yaml" -printf "-f%p\0")
cmd "${arr[@]}"
But to call a command with those filenames, I would just use xargs:
find ./ -type f -name "*.yaml" -printf "-f\0%p\0" | xargs -0 cmd