I often run into files with spaces in them and I want to rename them. Once again, there's a command that's appropriately named to do the job. I'm going to go over how to use the
rename command. Let's take a look at the files we're going to work with.
mike@shiner $ ls
foo bar.txt test this.txt
We have two files which are named 'foo bar.txt' and 'test this.txt'. We're going to use the following command to get rid of the spaces.
mike@shiner $ rename 's/ /_/' *.txt
The command takes two arguments. The first argument is a regular expression where the 's' stands for substitute. The contents between the first set of slashes represent what we're matching on. The '_' between the second set of slashes represent what we want to replace it with. The second argument, *.txt, tells
rename what files will be affected. The preceding command happily renders the following result.
mike@shiner $ ls
foo_bar.txt test_this.txt
Now let's say we want to replace the underscores with dashes. We can do this with the following command.
mike@shiner $ rename 's/_/-/' *.txt
mike@shiner $ ls
foo-bar.txt test-this.txt