Remove Spaces (or any character) from File Names in Linux

This is actually a pretty common thing to run into in a Linux file system.  It is especially prevalent in the files that are moved from another operating system (Usually Windows).  So if you get files that need to have a space or a character removed, the below snipped is a very simple, and handy way to fix this issue.

└─(11:26:40)-(~/Example)->ls
file 1.txt
file – 2.txt

So, from here we want to rename the file “file 1.txt” to “file_1.txt”.  This would be done as follows:

rename ‘s/ /_/g’ file 1.txt

This will remove any spaces in the file-name listed.  If you want to do all the files in a directory:

rename ‘s/ /_/g’ *

Here is an example output if we run it on all the files in the directory (as seen above):

└─(11:33:59)-(~/Example)->ls
file_1.txt
file_-_2.txt

 

Note:  If you are new to Linux; and you haven’t heard of the “sed” command, that is the syntax used in the command.  If you get comfortable with this, then you can easily learn sed, which is a great tool to have on the command line.