How to manage spaces and special characters in a file name
Method 1: quoting
This is very straightforward: put the file name in single quotes ( ‘ ) so spaces or special characters won’t bother you anymore:
$ cat ‘File With Spaces.txt’
See why the quotes are so important? If you don’t use them, cat tries to view three different files: File, With and Spaces.txt.
Or another example:
$ rm ‘File*.txt’
Here the quotes are even more important! Because * is a shell wildcard that matches any character, you’ll be in a big trouble if you don’t use the quotes. Without the quotes the shell removes File*.txt as intended, but in addition File.txt, File2.txt, File22.txt and others will get removed.
Method 2: escaping
Another way to deal with special characters in a file name is to escape the characters. You put a backslash ( \ ) in front of the special character or space. This makes the bash shell treat the special character like a normal character:
$ cat File\ With\ Spaces.txt
or:
$ rm File\*.txt
But what to do if the file name contains the \ character? Well, you escape it too!
$ rm File\\.txt
Of course you can also use the quotes:
$ rm ‘File\.txt’
It’s a matter of personal taste which method you use, quoting or escaping, but personally I prefer quoting. It’s much more straightforward in my opinion. However, quoting doesn’t always work. For example, if you want to use shell wildcards with a file that has special characters in its name, it’s impossible to use quoting because that would escape the wildcards as well, so in these cases it’s necessary to escape the special characters with a backslash.
Category: Tips for linux
