Wednesday, June 10, 2009

Padding zeros in file name using bash


Example 1
---------
Files in my current directory are:

$ ls | paste -
a.10.done
a.2.done
m.100.done
n.1.done


Required: Rename the above files to

a.0010.done
a.0002.done
m.0100.done
n.0001.done

i.e. make the "number part" of the filename equal width by padding the number with leading zeroes

The solution using awk and bash parameter substitution

for file in $(ls)
do
eval $(echo "$file"|awk -F'.' '{print "prefix="$1";sl="$2}')
mv $file $(printf "%s.%04d.%s\n" "$prefix" "$sl" "done")
echo "Renamed $file"
done


Reference:

- Read about awk and eval here and here
- A few posts on bash parameter substitution
- Why double brackets for arithmetic operations in bash ? Read here

Example 2
---------
Files in my current directory are:

$ ls | paste -
apl.1
apl.10
apl.100
apl.2
apl.5

Required: Rename the above files to

apl.0001
apl.0010
apl.0100
apl.0002
apl.0005

The solution:

for file in apl.*
do
psl='0000'${file#apl.}
psl=${psl:(-4)}
mv $file apl.$psl
done


Another way would be:

for file in apl.*
do
mv $file $(printf apl.%04d ${file#apl.})
done

2 comments:

Mahesh Kharvi said...

Jadu,

another way of doing.
1.
eval $(ls *done | awk -F"." '{printf("mv %s %s.%04d.done;\n",$0,$1,$2)}')
2.
eval $(ls apl.* | awk -F"." '{printf("mv %s apl.%04d;\n",$0,$2)}')

Jadu Saikia said...

@Mahesh, thanks.
Another reference:

for i in {1..10}; do printf "%03g " "$i";done

001 002 003 004 005 006 007 008 009 010

© Jadu Saikia www.UNIXCL.com