Saturday, March 6, 2010

Removing Spaces from file names

Recently I came across an interesting problem. I had photos of a recent trip in the directory pictures. The name of the files were as follows.

Image DSCN 10101
Image DSCN 10102
Image DSCN 10103
Image DSCN 10104

All the images were of the .JPG format. The size of each image was around 2.0 MB. Since I wanted it to upload it on the net, I decided to increase the compression level of the jpeg image using the convert command. I had around 70 files to be changed. I wrote a simple shell script to do this.


#!/bin/bash
for file in `ls -1`
do
convert -quality 50 $file new-$file
echo $file
done

I wrote this loop to iterate over all the file inside the pictures directory. I was taken by suprise when I ran this shell script. I got numerous errors. I found out that the variable file uses space as a de-limiter. Since the file name contains spaces, the complete name of the file was not in the $file variable. So first I had to remove the spaces in the file names of the pictures. I googled around and came across this handy command called rename.

The rename command is used to rename a file according to a perl kind of regular expression. To tackle my problem, the command used was,

$rename 's/ *//g' *.JPG

The above command searches for any white spaces in the file names. If present, it replaces it by null string. The syntax is similar to the search and replace syntax used in vi.
hit counter