Convert spaces to underscores using a script

Convert spaces to underscores using a script

I had several files that had spaces in their names and I wanted to convert those spaces to underscores. Here’s how I did it.

If you don’t have one already, make a bin directory in your home directory:

cd
mkdir bin

In your /home/<username>/bin directory, create a new file, called nospace:

cd ~/bin
pico nospace

In the nospace file, add the following lines (notice that it is *2* spaces after the backslash):

for i in `ls -1 *`
do
  rename \  _ *.$1
done

Save your changes and close the nospace file. Now we need to make the file executable.

chmod 766 nospace

If you do an ls -l, you should now see the following:

-rwxrw-rw- 1 <username> <groupname> <filesize> <date> nospace

Now cd to a directory that has file with spaces in their names and enter the following:

nospace txt

Every file ending in .txt should now have underscores instead of spaces in the filename.

If you want to change just the pdf files, enter the following:

nospace pdf

If you want to change every single file, regardless of file extension, enter the following at the command line:

nospace *

If you wanted to change underscores to spaces, change rename \  _ *.txt in the script to rename _ \  *.txt (Again, notice that there were *2* spaces after the backslash).

whoami
Stefan Pejcic
Join the discussion

I enjoy constructive responses and professional comments to my posts, and invite anyone to comment or link to my site.