Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert month from Aaa to xx in little script with awk

I am trying to report on the number of files created on each date. I can do that with this little one liner:

ls -la foo*.bar|awk '{print $7, $6}'|sort|uniq -c

and I get a list how many fooxxx.bar files were created by date, but the month is in the form: Aaa (ie: Apr) and I want xx (ie: 04).

I have feeling the answer is in here:

awk '
BEGIN{
   m=split("Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec",d,"|")
   for(o=1;o<=m;o++){
      months[d[o]]=sprintf("%02d",o)
    }
format = "%m/%d/%Y %H:%M"
}
{
split($4,time,":")
date = (strftime("%Y") " " months[$2] " " $3 " " time[1] " " time[2] " 0")
print strftime(format, mktime(date))
}'

But have no to little idea what I need to strip out and no idea how to pass $7 to whatever I carve out of this to convert Apr to 04.

Thanks!

like image 921
SherpaPsy Avatar asked Dec 04 '22 17:12

SherpaPsy


2 Answers

Here's the idiomatic way to convert an abbreviated month name to a number in awk:

$ echo "Feb" | awk '{printf "%02d\n",(index("JanFebMarAprMayJunJulAugSepOctNovDec",$0)+2)/3}'
02

$ echo "May" | awk '{printf "%02d\n",(index("JanFebMarAprMayJunJulAugSepOctNovDec",$0)+2)/3}'
05

Let us know if you need more info to solve your problem.

like image 163
Ed Morton Avatar answered Jun 02 '23 19:06

Ed Morton


Assuming the name of the months only appear in the month column, then you could do this:

ls -la foo*.bar|awk '{sub(/Jan/,"01");sub(/Feb/,"02");print $7, $6}'|sort|uniq -c
like image 40
tommy.carstensen Avatar answered Jun 02 '23 20:06

tommy.carstensen