How to Find and Collect All MP3 Files into a Single Directory [Supports Spaces and Japanese Filenames]

You might want to gather various `.mp3` files—such as music or recordings—into a single location, ignoring the existing directory structure. A combination of the `find` and `mv` commands is very handy for this.

However, you need to be careful if the filenames contain spaces, Japanese characters, or symbols. If you process them directly with a standard `for` loop or similar approach, unintended splitting will occur and the command will fail.

In this article, I will introduce an actual error example I encountered and show you how to safely move `.mp3` files to a single location.

目次

Failure Example: A for-loop combined with find is vulnerable to spaces

for f in $(find . -name "*.mp3"); do
mv "$f" ./music/
done

With this syntax, if the filenames contain spaces or Japanese characters, they get split up, resulting in a series of errors like the ones below:

mv: cannot stat `Classic/Classic': No such file or directory
mv: cannot stat `#13': No such file or directory

The Correct Approach: Use -print0 and read -d ''

mkdir -p ./music

find /mnt/main/share/0common/00_swaps/iTunes-Share/Music/EMI\ Classic/ -type f -name "*.mp3" -print0 | \\
while IFS= read -r -d '' file; do
echo "$file"
mv "$file" ./music/
done
    • -print0: Uses NULL (`\\0`) as the delimiter for filenames
    • -d '': Correctly reads inputs delimited by NULL
  • "$file": Encloses the filename in double quotes to prevent it from being split
  • IFS=: Disables extra delimiters (spaces and newlines)

How to Safely Handle Duplicate Filenames

If a file with the same name already exists in the destination, `mv` will overwrite it. To prevent this, a script that includes renaming logic is very useful.

mkdir -p ./music

find . -type f -iname "*.mp3" -print0 | while IFS= read -r -d '' file; do
base=$(basename "$file")
dest="./music/$base"
if [[ -e "$dest" ]]; then
i=1
while [[ -e "./music/${i}_$base" ]]; do
((i++))
done
dest="./music/${i}_$base"
fi
mv "$file" "$dest"
done

Conclusion

  • While find + mv is extremely powerful, you must watch out for the pitfalls of spaces and special characters.
  • The syntax combining -print0 and read -d '' might look a bit niche at first glance, but it is an essential skill that achieves both safety and versatility.
  • Once you learn the method in this article, you can easily apply it to organize other files such as images, audio, and PDFs.