awk study(9)

来源:互联网 发布:淘宝托管费用 编辑:程序博客网 时间:2024/05/18 03:50

 1.5 A more complex example

       Now that we have mastered  some simple  tasks, let's look at what typical awk programs do.This example shows how awk can be used to summarize, select and rearrange the output of another ultility. It uses features that havn't been covered yet, so don't worry if you don't understand all the details.

     ls -l | awk '$6 == "Nov" { sum += $5 }
END { print sum }'

This command prints the total number of  bytes in all the files  in the current directory that were last modified in November(any of year), The 'list -l' part of this example is a system command that gives you a listing of  files in a derectory, include the file size  and the data the file was  last modified.Its output look like this:

     -rw-r--r--  1 arnold   user   1933 Nov  7 13:05 Makefile
-rw-r--r-- 1 arnold user 10809 Nov 7 13:03 awk.h
-rw-r--r-- 1 arnold user 983 Apr 13 12:14 awk.tab.h
-rw-r--r-- 1 arnold user 31869 Jun 15 12:20 awk.y
-rw-r--r-- 1 arnold user 22414 Nov 7 13:03 awk1.c
-rw-r--r-- 1 arnold user 37455 Nov 7 13:03 awk2.c
-rw-r--r-- 1 arnold user 27511 Dec 9 13:07 awk3.c
-rw-r--r-- 1 arnold user 7989 Nov 7 13:03 awk4.c

The first field contains the read-write permissions of the file,the second field contains the number of links to the file, the third field identifies the owner of the file, the forth field identifies the group of the files, the five field contains the size of the file in bytes, the sixth , seventh ,eighth field contain the month, day, and the time, respectly,that the file was last modified.Finally, the ninth field contains the name of the file.

    The '$6 == "Nov" ' in our awk program is an expression that tests whether the sixth fields of the output from 'ls -l' command match the string 'Nov'. Each time the line has sting 'Nov' as its six field, the action "sum += $5" is performed, this adds the fifth field(file size) to the variable sum . As a result ,when awk finishs reading all the input lines, the result will be the total of the size of the files whose lines matched the pattern(This works because awk  variables are automatically inintialized to zero)

    After the last line of output from 'ls' has been processed,the END rule executes and prints the value of sum,  in this example the sum  is 80600.

    Those more advanced awk technique are covered in later sections,Before you can move on to more advanced awk programs, you have to  know  how awk interprets your input  and  display your output, by mainiputlating fileds and usting print statement, you can produce some very useful and impressive-looking report.