Execute command on files with spaces in Bash

Posted on January 1, 2015

All UNIX users have a love for batch-processing files. I had to do some processing on a few hundred different files. However some of the people who submitted the files, sadly, used filenames with spaces in them. Usually one would do something like this:

for file in *.txt; do
    cat file

But since bash (or the much better zsh) will split using whitespaces, files with spaces will not be processed properly. I looked further and thought maybe the xargs command will do the trick:

find . -name "*.txt" | xargs -I file cat file

But filenames with spaces in them still do not work. After some heavy researching, and reading long man pages I found the following solution:

find . -name "*.txt" -print0 | xargs -0 -I file cat file 

This will separate each filename with the null character, thus allowing xargs to process filenames with whitespaces in them!

blog comments powered by Disqus