I am using zsh as a shell.
I would like to execute the unix find command and put the result into a shell array variable, something like:
FILES=($(find . -name '*.bak'))
so that I can iterate over the values with something like
for F in "$FILES[@]"; do echo "<<$F>>"; done
However, my filenames contain spaces at least, and perhaps other funky characters, so the above doesn't work. What does work is:
IFS=$(echo -n -e "\0"); FILES=($(find . -name '*.bak' -print0)); unset IFS
but that's fugly. This is already a bit beyond my comfort limit with zsh syntax, so I'm hoping someone can point me to some basic feature that I never knew about but should.
I tend to use read for that. A quick google search showed me zsh also seem to support that:
find . -name '*.bak' | while read file; do echo "<<$file>>"; done
That doesn't split with zero bytes, but it will make it work with file-names containing whitespace other than newlines. If the file-name appears at the very last of the command to be executed, you can use xargs, working also with newlines in filenames:
find . -name '*.bak' -print0 | xargs -0 cp -t /tmp/dst
copies all files found into the directory /tmp/dst. Downside of the xargs approach is that you don't have the filenames in a variable, of course. So this not always applicable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With