awk and leading zeroes

I have the following script that renames filenames like:
blah_bleh_91_2011-09-26_00.05.43AM.xls
and transforms it in:
91_20110926_000543_3_blih.xls

for a in *.xls;
do
b="$(echo "${a}" | cut -d '_' -f4)"
dia=`echo ${b} | cut -c9-10`
mes=`echo ${b} | cut -c6-7`
anio=`echo ${b} | cut -c1-4`
nueva_fecha="${anio}${mes}${dia}" 

c="$(echo "${a}" | cut -d '_' -f5)"
hora=`echo ${c} | cut -c1-2`
min=`echo ${c} | cut -c4-5`
seg=`echo ${c} | cut -c7-8`
nueva_hora="${hora}${min}${seg}" 

echo $a | awk -F_ '{ print "mv -v "$0" "$3"_"'${nueva_fecha}'"_"'${nueva_hora}'"_blih.xls" }' | bash

done

It works fine except in the particular case of the example. When the hour is "00.0x" it does not work properly.

Any thoughts?

Thanks!

How about this:

ls *.xls | awk -F_ '
{
    nueva_fecha=substr($4,1,4) substr($4,6,2) substr($4,9,2)
    nueva_hora=substr($5,1,2) substr($5,4,2) substr($5,7,2)
    print "mv -v " $0 " " $3 "_" nueva_fecha "_" nueva_hora "_blih.xls" }'
1 Like

Thats because the leading 0s make it an octal number inside of awk and as you can guess...000543 in octal is 355 in decimal...besides why make it so tedious when a single awk command is enough for this...

echo *.xls | awk -F_ '{
    s=$0
    t="_blih.xls"
    gsub("-","",$4)
    gsub("[PAM.xls]","",$5)
    d=$3FS$4FS$5
    system("mv -v "s" "d""t)
}'

My thoughts exactly :slight_smile:

I thought I'd toss in the reason why the O/P was having issues though. The source of the problem is the awk

awk -F_ '{ print "mv -v "$0" "$3"_"'${nueva_fecha}'"_"'${nueva_hora}'"_blih.xls" }' 

nueva_hora contains 000543 which when placed on a command as a number, rather than as a string, is interpreted as an octal value and the leading zeros are 'absorbed.' To see this, run this simple awk:

awk ' BEGIN { print 000543 }'

Opening and closing the single quotes to insert shell variables helps to lead to this problem which is why doing that is one of my pet peeves. Assuming the awk being used is modern, then this code would have prevented the problem (though I still like Chubler_XL's solution better):

awk  -v n_hora="$nueva_hora" -v n_fecha="$nueva_fecha" -F_ '{ 
print "mv -v " $0 " " $3 "_" n_fecha "_" n_hora "_blih.xls" }' 
1 Like

Thank you guys!