HOWTO Work with filenames containing whitespace

HOWTO Work with filenames containing whitespace

From Consultancy.EdVoncken.NET

Jump to: navigation, search

Sometimes. you encounter filenames with whitespace. Unix normally treats whitespace as a "separator", or Input Field Separator (IFS). This means that your precious filenames are treated as multiple separate filenames, often leading to hilarious results - or a quick dash to the backup tapes.

Take one or more of the following steps to prevent strange things from happening:

  1. Put quotes around the filename
  2. "Escape" whitespace in the filename

Finally, I will show an example where "find" is used to process multiple files.

Put quotes around the filename

You can tell Unix to treat a string as one parameter by enclosing it in quotes.

Instead of:

 # mv Filename with spaces Destination filename
 mv: target `filename' is not a directory

use:

 # mv "Filename with spaces" "Destination filename"

Escape whitespace in the filename

You can tell Unix to treat the whitespace as a "literal" whitespace by "escaping" the character using the backslash.

Instead of:

 # mv Filename with spaces Destination filename
 mv: target `filename' is not a directory

use:

 # mv Filename\ with\ spaces Destination\ filename

Processing multiple files using "find"

When processing a number of files that may contain whitespace in their names, you need to take special precautions:

Instead of:

 # find . -name "*.bak" | xargs rm

use:

 # find . -name "*.bak" -print0 | xargs -0 rm

Here, we instruct "find" to generate output with ASCII Null characters separating each item of output. We then instruct the "xargs" command to take Null-separated input. This way, spaces and other characters in filenames are no longer a problem.