Spaces in filenames?

dos2unix

Well-Known Member
Joined
May 3, 2019
Messages
3,322
Reaction score
3,063
Credits
29,547

Handling Spaces in Linux Filenames​

In Linux, filenames can contain spaces, which can sometimes cause issues when using the command line. While graphical file managers like Nautilus, Nemo, or Dolphin handle spaces seamlessly, the command line requires special attention.

Common Problems with Spaces in Filenames​

When you download files or create them with spaces in their names, you might encounter difficulties when trying to manipulate these files using the command line. For example, a simple command like ls might not work as expected:

Code:
 ls My File.txt

This command will result in an error because ls interprets My and File.txt as two separate arguments.

Handling Spaces with Backslashes​

One way to handle spaces in filenames is by escaping them with backslashes (\). This tells the shell to treat the space as part of the filename:

Code:
 ls My\ File.txt

Handling Spaces with Double Quotes​

Another method is to enclose the filename in double quotes. This also ensures that the shell treats the entire string as a single argument:

Code:
 ls "My File.txt"

Renaming Files to Avoid Spaces​

To avoid dealing with spaces altogether, many users rename their files using underscores (_), dashes (-), or by removing spaces entirely. Here are some examples:

  • Using underscores: My_File.txt
  • Using dashes: My-File.txt
  • Removing spaces: MyFile.txt
  • Using camel case: ThisIsMyFile.txt

Bash Script to Replace Spaces with Underscores​

Here's a simple bash script that finds all files in the current directory with spaces in their names and replaces the spaces with underscores:

Code:
 #!/bin/bash

for file in *\ *; do if [ -e "$file" ]; then mv "$file" "${file// /_}" fi done

Save this script to a file, for example rename_spaces.sh, and make it executable:

Code:
 chmod +x rename_spaces.sh

Then run the script in the directory where you want to rename the files:

Code:
 ./rename_spaces.sh

This script will rename all files with spaces in their names by replacing the spaces with underscores.
 


I miss in your description that what a file manager do via drag + drop :
Code:
ffmpeg -i '/home/richard/Videos/Escape Plan 2 Hades.mp4'
or written in terminal and add quotation marks :
Code:
ffmpeg -i "./Escape Plan 2 Hades.mp4"

Never had problems with this syntax. I work every day with video/audio files, space will be there "default", no need to rename the files.

Also for mp3 :

Common & John Legend - Glory.mp3
Electric Light Orchestra - Boy Blue.mp3
Electric Light Orchestra - Can't Get It Out Of My Head.mp3
Electric Light Orchestra - Dark City.mp3
Electric Light Orchestra - Eldorado Finale.mp3
Electric Light Orchestra - Eldorado Instrumental Medley.mp3
Electric Light Orchestra - Eldorado.mp3
Electric Light Orchestra - Eldorado Overture.mp3
Electric Light Orchestra - Illusions In G Major.mp3
Electric Light Orchestra - Laredo Tornado.mp3
Electric Light Orchestra - Mister Kingdom.mp3
Electric Light Orchestra - Nobody's Child.mp3
Electric Light Orchestra - Poor Boy (The Greenwood).mp3
Fu Manchu-Mongoose.mp3
Funkadelic - Maggot Brain.mp3
Gandalf's Fist - Gardens of the Lost.mp3
Garbage - Crush.mp3
Garbage - Only Happy When It Rains.mp3
Garbage - Queer.mp3
Garbage - Stupid Girl.mp3
Gary Clark Jr. - Bright Lights.mp3
Gary Clark Jr. - Numb.mp3
Gaz Coombes - Walk The Walk.mp3
George Michael - Father Figure.mp3
GHOULTOWN - Drink With The Living Dead.mp3
Ghoultown - Walkin through the desert.mp3
Golden Earring - Twilight Zone .mp3
Gondwana - Sentimiento Original.mp3
Good Looking Animals How You Do It.mp3
Gorillaz - Tomorrow Comes Today.mp3
Gossip - Heavy Cross.mp3
Gotye - Somebody That I Used To Know .mp3
Gov't Mule - Drivin' Rain.mp3
Grand Avenue - Bullet.mp3
Grayson Capps - Ike.mp3
Green Day - 21 Guns.mp3
Green Day - Good Riddance.mp3 ...
 
My pet peeve: spaces in filenames. I always use dashes or camel case and underscores as separators. It actually offends me. Like other characters that don't belong in file names, we have Microsuck to thank as they were the biggest proponents... Then came the "mobile revolution" (by that I mean regression) and our phones were encouraging this insane behaviour, too. Even my music is renamed: artist-name_yyyy_track-name or yyyy-[mm | part[a-z]] if there were more than one albums released that year or if it's a multi-disc collection.

...

I miss in your description that what a file manager do via drag + drop :
Code:
ffmpeg -i '/home/richard/Videos/Escape Plan 2 Hades.mp4'
or written in terminal and add quotation marks :
Code:
ffmpeg -i "./Escape Plan 2 Hades.mp4"

Never had problems with this syntax. I work every day with video/audio files, space will be there "default", no need to rename the files.
Interesting music collection you have there!
To to clarify, though:
  • Spaces aren't default, they're optional (but advised against). The naming convention of files depends on the source. There is no default as such. Only standards per distributor or software conventions (and ffmpeg has none when it comes to files).
  • Nobody said you have to remove spaces, @dos2unix provided the script for people who don't like spaces in their filenames because there are plenty people with preferences and some newcomers may actually need to remove spaces and not know-how.

It's a personal choice, at least for most desktop users.

PS: you don't need './' when passing a filename as an argument for ffmpeg or any piece of software. The reason we use './' for executables, example ./run_this.sh, is because historically, you would call /path/to/executable if it was not in PATH, and the '.' is a shorthand for current working directory (like '..' means parent). The slash, '/' completes the path as expanded. EG: say . expands to my home. That would be "/home/me" (no slash). And that is why we run things with './' .
 
but advised against
Who did ?
Please refer to common download platforms for video, audio, all ways you will find spaces in file names.
No TV, BD-Record-Device ...have a problem to read files with "spaces" e,g, via DLNA.

It's a personal choice, at least for most desktop users.
Where is the statistic ? ;)

It is not so important what to use, and it is not forbidden by linux but better readable (directories, filenames) and compatible with the rest of the world.
(Also, I remember me to see the first filename withe spaces, its allowed ? I asked me, obviously , from then on ...).
 
Last edited:
It is not so important what to use, and it is not forbidden by linux but better readable (directories, filenames) and compatible with the rest of the world.
Who did ?
(but advised against).
The reason is largely historical - WAY back in the mists of time spaces were not allowed in filenames, so spaces were used as keyword / filename separators. Future shell interpreters had to be reverse-compatible with old scripts, and thus we are stuck with the headache we have today.
A lot of the reasons are historical. That doesn't mean that they don't make sense today.

I use some programs that generate files with spaces in them, sure I could adjust the output but that would cause other issues with other things, but I still think spaces in file names or directories are a PITA on Linux because when dealing with them on the command-line you either have to escape them or put them in quotes and when dealing with them. I have also found when dealing with spaces in directories or filenames in scripts it cause unexpected behavior when you run your script and the shell doesn't interpret something the way you think it should have.

We don't use spaces in website urls because of rfc1738:
Unsafe:
Characters can be unsafe for a number of reasons. The space
character is unsafe because significant spaces may disappear and
insignificant spaces may be introduced when URLs are transcribed or
typeset or subjected to the treatment of word-processing programs.
The characters "<" and ">" are unsafe because they are used as the
delimiters around URLs in free text; the quote mark (""") is used to
delimit URLs in some systems. The character "#" is unsafe and should
always be encoded because it is used in World Wide Web and in other
systems to delimit a URL from a fragment/anchor identifier that might
follow it. The character "%" is unsafe because it is used for
encodings of other characters. Other characters are unsafe because
gateways and other transport agents are known to sometimes modify
such characters. These characters are "{", "}", "|", "\", "^", "~",
"[", "]", and "`".

Lastly just food for thought, we don't use spaces in domain names and neither in website urls. So why use them in directory names and filenames? And why don't we use them in domain names and website urls if we use them today in directory and file names?
 
Lastly just food for thought, we don't use spaces in domain names and neither in website urls. So why use them in directory names and filenames? And why don't we use them in domain names and website urls if we use them today in directory and file names?
For "c" no spaces are allowed, except for strings. Your logic would be, it should be also forbidden in file/directory-names. Why its not ? Because the one has nothing to do with the other.
Yes of course the tradition is so, but please give me an example for which linux distrubution it is a problem, a known issue ?(except scripts), for normal use via file manager ?
And if you can give me an example, yes we have to exclude it for this example.
 
for normal use via file manager ?

Keep in mind, over the vast majority of Linux installs are server installs with no GUI.



99% percent of the Linux systems I use have a no GUI.
 
99% percent of the Linux systems I use have a no GUI.
To use GUI or only the terminal, it is not an "either or", it is a question of how it does help me in my daily work, speed up my work.
Some people have said, "he programs with the mouse" yes I did, for the key-board enthusiast, as foreign as possible.
 
Your logic would be, it should be also forbidden in file/directory-names. Why its not ? Because the one has nothing to do with the other.
Website urls are technically locations or directories which a webserver can access.
Lastly just food for thought, we don't use spaces in domain names and neither in website urls. So why use them in directory names and filenames? And why don't we use them in domain names and website urls if we use them today in directory and file names?
Lastly with this I was only trying to make us try and see it from both sides and to think about outside the box no matter what an RFC says. I wasn't trying to argue anything I was just trying to let readers in this topic think outside of the box. So it's not my logic just my way of saying lets look it from both sides no matter what you think, whether you are for or against.

sure I could adjust the output but that would cause other issues with other things, but I still think spaces in file names or directories are a PITA on Linux because when dealing with them on the command-line you either have to escape them or put them in quotes and when dealing with them.
I alo said I use directories with spaces in them for certain applications because of how they can effect other applications who use those directories based on directory naming. So I do use it directories with spaces in them but when it doesn't effect other things I still prefer to use directories without spaces.

I also mentioned why it is that some people think that it is not allowed and it also mentions that it's because of historical reasons. Old habbits die hard I guess. I never argued that no one should use only file and diretory names without spaces and that it's a sin to do so. I would say do what you prefer, I only use spaces in file and directory names when an application expects it for some reason, if they don't then I don't. That's my way of doing it, you have your way of doing it and @Fanboi has his way of doing it.

Keep in mind, over the vast majority of Linux installs are server installs with no GUI.
The only install I have with gui are my desktop and laptop.
 
@Gloster Before we go on I think it's important that I acknowledge the language barrier. It's become patently obvious reading this thread that English is not your native language. I did not realise because "alot" (deliberate) of people post poor English in this forum. Even I type things barely legible if I'm speed typing on a touch screen.

So it's clear you misunderstood the thing about the script in the OP, I then misunderstood your assertion, you then, it's obvious, have misunderstood my context.
If you are using DeepLearn already I suggest you use multiple translators and check if there's some nuance. If not, I suggest you switch as DeepL is generally advised by most folk on the forum.

Be that as it may, I'll address your questions and then I'm hoping we can leave it at that.

but advised against
Who did ?
For the sake of readers, aside from everything the @f33dm3bits posted here (post #5), how about MIT, ya know only one of the most notable universities for computer science, maths, etc. in the world, no biggie.

Please refer to common download platforms for video, audio, all ways you will find spaces in file names.
Why? That has zero relevance. Instead: Please refer to me some platforms where I can buy spotted day-old chicks and seeds... Okay, done amusing myself. Please take that last line in the spirit it was intended.

So I'm assuming you missed the context. I was not referring to any specific service (and I realise now what you meant by "default", too). This thread is about computing, not consumer electronics or media download sites/services.
So let's just quickly explain it:
There are no "defaults" for A/V files, only "conventions" for sources (and for the under-30s, there are sources besides "download platforms"). Here's an example: many older devices like cameras had no spaces in filenames because their firmware didn't support it because implementing it was an extra pain and files were handled internally. Here's another example: anywhere people who avoid spaces distribute stuff so it windows up as. That's what I meant by:
Fanboi: The naming convention of files depends on the source. There is no default as such. Only standards per distributor

It's a personal choice, at least for most desktop users.
Where is the statistic ? ;)
Now that comment here made me realise there was a language barrier. I know how you misinterpreted it, but I'm going to pretend I didn't just to amuse myself.
Answer: The statistic is everyone who uses a PC, Android, iOS, and similar devices.
Amusing myself finished.
Your translator probably turned that sentence into "it's the choice for most desktop users" in and already out-of-context translation. What I actually meant is:
The use of spaces = personal choice. This applies to most* desktop users.

*Most, not all because I don't know if there is some weird homebrew OS/software preloaded onto some weird device that may still limit you to 8 dot 3 filenames. That and there are some like me who cannot stay sane with spaces, even if they looked better.

Okay hope that clears it up. Mutual misunderstanding, @Gloster missed the context, I -- well, we all -- missed his/her context, and then s/he missed ours again. Somewhere between all this, pieces were understood, frictions arose, etc., etc. but I hope now I've managed to explain things clearly and hopefully dowse the flames while adding both a little humour and some useful info for anyone stumbling on this thread.

Cheers,
- J
 


Top