Bash: processing filenames with white spaces

A Televideo ASCII character mode terminal, usi...

Image via Wikipedia

It is often necessary to read a file with bash, and act upon the entire line. There are many different ways to do this, but I’ll outline one of the simpler methods, both suitable for stacking on a single command line.

For this exercise I’ll assume the file is a list of files that we need to execute a command on.

# cat file.lst |while read line; do echo "${line}"; done
/tmp/file with space.txt

All we’ve managed to do here is cat the file. Alternately we could move the cat to the end of the while loop as follows:

# while read line; do echo "${line}"; done < <(cat file.lst)
/tmp/file with space.txt

The beauty of this solution lies in the handling of whites paces in a filename, a simple for loop would have broken the filenames in separate tokens.

Tagged with: ,
Posted in Code, Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: