1

I'm trying to find the average number of files per day.

The following script works:

#!/bin/sh
ls -l | grep "^-" | awk '{
key=$6$7
freq[key]++
}
END {
for (date in freq)
               printf "%s\t%d\n", date, freq[date]
}'

When I add do and done for the for loop like below:

#!/bin/sh
ls -l | grep "^-" | awk '{
key=$6$7
freq[key]++
}
END {
for (date in freq)
do
               printf "%s\t%d\n", date, freq[date]
done
}'

I get the below error:

awk: cmd. line:8: done
awk: cmd. line:8: ^ syntax error

How to write multi-line for loop statements inside END block of awk command?

Solution:

We need to use { and } to start and end for loop in END block of awk command.

#!/bin/sh
ls -l | grep "^-" | awk '{
key=$6$7
freq[key]++
}
END {
for (date in freq)
{
        count=count+1
        total=total+freq[date];
        printf "%s\t%d\n", date, freq[date]
}
printf "Average files per day : %d\n",(total/count)
}'

2 Answers 2

3

There is no done in awk syntax at all, and do just as do statement while (condition).

You need curly brackets instead:

for (date in freq) { cmd1; cmd2; cmd3; }
0

Please consider that, in general, parsing ls output is problematic.

See Why you shouldn't parse the output of ls (plus linked pages).

As a solution for manipulating date/time of files, you can use GNU find (where available) and use GNU extesion like -printf "%T@" to get unix epoch time or output time in easy parsable format. (check man find or read it here ).

--EDIT: Kevin point out this :

BSD find (and other implementations) do not have this functionality. But it's possible to use stat (where present) to obtain the same informations. Check man.

--EDIT END

As example you can do samething like this:

find . -maxdepth 1 -type f -printf "%TY%Tm%Td-%TH%TM%TS" 

to obtain modification times in YYYYMMDD-HHMMSS format.

6
  • BSD find does not have anything equivalent to -printf, the only way to get it to print time is -ls, and then you need to parse that.
    – Kevin
    Jun 23, 2013 at 16:00
  • Or, using external utils, find . -type f -exec stat -f '%Sm' {} +
    – Kevin
    Jun 23, 2013 at 16:10
  • @ Kevin : I do not undestand your remark: using external utility like find is exactly what I'm trying to suggest. But not all find utility on different *nix have this feature.
    – DavAlPi
    Jun 23, 2013 at 16:14
  • Your post seemed to imply that BSD find had some functionality more or less equivalent to printf, I was pointing out it doesn't. By "external utility" I was referring to stat, external to find.
    – Kevin
    Jun 23, 2013 at 16:21
  • @ Kevin : Ok, understood, it is not in BSD find. I'll edit and attribute.
    – DavAlPi
    Jun 23, 2013 at 16:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .