How to work on Linux with filenames that contain blanks

Personally, I always try to avoid filenames with spaces, usually using underscores or dashes in places where less space-phobic people would use them. The filenames are still easy to decipher, and I don’t have to bother with quoting them when I want to use them. As a result, some of my files look like this:

locking-accts
Lost_World

I also rarely add .txt File extensions at the end of text files unless I plan to share them with my Windows system.

Use quotation marks

However, if spaces in filenames are preferable for some reason, there are several easy ways to work with them. To refer to existing files, you can enclose the filenames in single or double quotes. You can even simplify this by starting with a double quote, typing as much of the filename as necessary to distinguish it from other files, and then pressing Tab to initiate filename completion. For example, if you type part of a filename, as shown in the following example, and then press Tab, the rest of the filename should be added to the beginning of “file n”:

$ head -2 “file n<tab>

You should then see the full filename along with other files that match the pattern:

$ head -2 “file name with blanks”
This is the content of the file. It should be what you expected to see
or maybe not.

Using single quotes works just as well as double quotes. Since the quotes aren’t part of the filenames, it doesn’t matter which ones you use.

$ head -2 ‘file name with blanks’

Use backslashes

A third option to consider is using backslashes before each space in the filename.

Copyright © 2022 IDG Communications, Inc.

Leave a Reply

Your email address will not be published. Required fields are marked *