Execute command on files with spaces in Bash

Posted on January 1, 2015

All UNIX users have a love for batch-pro­cessing files. I had to do some pro­cessing on a few hun­dred dif­ferent files. How­ever some of the people who sub­mitted the files, sadly, used file­names with spaces in them. Usu­ally one would do some­thing like this:

for file in *.txt; do
    cat file

But since bash (or the much better zsh) will split using white­spaces, files with spaces will not be processed prop­erly. I looked fur­ther and thought maybe the xargs com­mand will do the trick:

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

But file­names with spaces in them still do not work. After some heavy re­search­ing, and reading long man pages I found the fol­lowing so­lu­tion:

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

This will sep­a­rate each file­name with the null char­ac­ter, thus al­lowing xargs to process file­names with white­spaces in them!

blog comments powered by Disqus