How To Handle with Spaces in File Names in Linux Shell Scripts

Spaces in file names can be a headache. Say you have the following files with spaces in the file names:
    jknight@shadowbox:/tmp$ ls -1
    1 .txt
    2 .txt
    3 .txt
    4 .txt
    5 .txt
and you want to loop over them. How many times have you tried this?
    jknight@shadowbox:/tmp$ for file in $(find . -iname "*.txt"); do echo $file; done
    ./1
    .txt
    ./2
    .txt
    ./3
    .txt
    ./4
    .txt
    ./5
    .txt
In effect, this splits on spaces into an array, then loops over it: most definitely not what we wanted.  Try piping to a "while read" instead:
    jknight@shadowbox:/tmp$ find . -iname "*.txt" -print | while read file;do echo $file; done
    ./1 .txt
    ./2 .txt
    ./3 .txt
    ./4 .txt
    ./5 .txt


| Comments (0)TrackBacks (0)

0 TrackBacks

Listed below are links to blogs that reference this entry: How To Handle with Spaces in File Names in Linux Shell Scripts.

TrackBack URL for this entry: http://www.rootsilver.com/mt-tb.cgi/29

Leave a comment