Monday, December 29, 2008

Bash scripting :: Handling filenames with spaces


The following script moves a specified amount of files from the currect directory to a specified directory. I had a lots of images saved in one folder. Accessing the folder used to take a long time. So I decided to put the files chronologically in seperate folders. The challenge was - lots of my files had spaces in their names. So, a normal "for i in `ls -t`" does not work. So, I came up with the following work around. So far it works pretty good ;)



 1 #!/bin/bash
 2
 3 my_space="XXYYZZ"
 4 me=`basename $0`
 5
 6 if [ -z $1 ] || [ -z $2 ];then
 7         echo
 8         echo "[*] usage:  $me  dirname how_many"
 9         echo
10         exit
11 fi
12
13 if [ ! -d $1 ];then
14         echo
15         echo "[*] '$1' does not exist."
16         echo
17         exit
18 fi
19
20 ii=`ls -t1 | grep -v $me | sed "s/ /$my_space/g"`
21
22 c=0
23 for i in $ii
24 do
25         c=$((c+1))
26         n=`echo $i | sed "s/$my_space/ /g"`
27         echo -n "[$c]  "
28         mv -v -f "$n" $1
29         if [ $c -ge $2 ];then
30                 exit
31         fi
32 done
33

0 comments:

Post a Comment