I have a directory which contains multiple files with spaces in their names. I want to find a pattern in the name and those file will be moved to some other directory. Now t
Sometimes, the logic to insert in the body of the loop could be complex enough to warrant an actual bash loop.
Here is a solution that works that way:
find . -maxdepth 1 -name "*$pattern*xlsx" -type f | while IFS= read -r file
do
mv "$file" $destination/
done
Edit: kudos to @KamilCuk for the IFS=, to handle filenames with leading and trailing whitespace, and -r, to handle filenames with escaped backspace characters.
Known limitation: this solution will not work for filenames that have embedded newlines. For such cases, see the other answers to this question.
Solution from @Charles Duffy in comments to Moving files with whitespace what will work even with newlines in the file names:
-print0 to the find command to terminate records with the NULL character-d '' to the read command to read records terminated by NULLfind . -maxdepth 1 -name "*$pattern*xlsx" -type f -print0 | while IFS= read -r -d '' file
do
mv "$file" $destination/
done