Monday, May 13, 2013

Removing file name spaces using $IFS Bash shell variable.

At some point all Linux users need to deal with file name spaces, specially with movies or pictures. Using the shell variable IFS we can easily remove those and solve the issue. In this example, assuming I have all my pictures in the current folder, I will remove the space of my pictures in one :

$ ls -l *jpg
-rw-r--r-- 1 amartin amartin   22175 May 10 09:08 foto 1.jpg
-rw-r--r-- 1 amartin amartin   22175 May 10 09:08 foto 2.jpg
-rw-r--r-- 1 amartin amartin   22175 May 10 09:08 foto 3.jpg

 $ IFS=$(echo -en "\n\t");for file in `ls *jpg`; do newname=`echo $file | sed -e 's/ //g'`; cp "$file" $newname; done

$ ls -ltr *jpg
-rw-r--r-- 1 amartin amartin   22175 May 10 09:08 foto 1.jpg
-rw-r--r-- 1 amartin amartin   22175 May 10 09:08 foto 2.jpg
-rw-r--r-- 1 amartin amartin   22175 May 10 09:08 foto 3.jpg
-rw-r--r-- 1 amartin amartin   22175  May 10 10:07 foto1.jpg
-rw-r--r-- 1 amartin amartin   22175 May 10 10:07 foto2.jpg
-rw-r--r-- 1 amartin amartin   22175 May 10 10:07 foto3.jpg


If we would like a dash '-' or any other character we just need to replace the sed command for sed -e 's/ /-/g'.

The IFS variable defaults to space, tab and new line in Debian:

$ echo "$IFS" | cat -TE
 ^I$
$

Or the equivalent:

$ IFS=$(echo -en " \n\t")

We just removed the space in between the " and \n from the IFS (echo -en "_\n\t") to make this example work.

No comments:

Post a Comment