Imagine if you have white spaces in
I found myself in a situation where I had several files with spaces in their name. As a Linux user, you know how painful it is to deal with files with spaces in their name.
For this reason, I decided to replace all the spaces in the file names with underscore (_).
Now doing it manually might be fine if you have one or two files but if you have got multiple files, it’s better to go the command line way.
Renaming multiple files by replacing characters in the file name
As always, there can be multiple ways to do this and some methods might suit better for your needs.
My scenario is pretty straightforward. I have tens of files in a directory. I want to replace spaces with underscore in their names.
To do that, I suggest using the rename command in the following fashion:
rename 's/ /_/g' *
That’s it. One single line of command will solve the problem for you.
Let me explain how this command works.
The rename command works only on the file names. It uses regex for searching and replacing. Basically, you are telling to rename all the matches of space with
The interesting part is the asterisk(*). The asterisk tells you to rename matching files in the current directory.
But what if you want to rename all the matching files in sub-directories as well? In that case, you can use two asterisks like this:
rename 's/ /_/g' **
That’s it. Isn’t it sweet and simple? I hope you liked this quick Linux tip.