Generating Reports with awk

Back in Chapter 6, we showed you how to edit delimited files with awk, which is cool because it lets you extract specific pieces of information, such as names and phone numbers, from delimited files. As shown in Code Listing 17.4, you can also use awk to generate reports. We start with the information from an ls -la command, and then use awk to generate a report about who owns what

Code Listing 17.4. Use awk to generate quick reports.
[ejr@hobbes /home]$  ls -la | awk '{print$9 " owned by "   $3 } END { print NR "Total Files" } '
 owned by
. owned by root
.. owned by root
admin owned by admin
anyone owned by anyone
asr owned by asr
awr owned by awr
bash owned by bash
csh owned by csh
deb owned by deb
debray owned by debray
ejr owned by ejr
ejray owned by ejray
ftp owned by root
httpd owned by httpd
lost+found owned by root
merrilee owned by merrilee
oldstuff owned by 1000
pcguest owned by pcguest
raycomm owned by pcguest
samba owned by root
shared owned by root
22 Total Files
[ejr@hobbes /home]$

To Generate Reports with awk:

  • ls -la | awk '{print $9 " owned by "
    → $3 } END { print NR "
    → Total Files" }'
    

    Whew! In general, pipe ls -la to the long-winded awk command. (Yes, this is the origin of awkward.) awk then prints the ninth field ($9), the words “owned by,” then the third field ($3), and at the end of the output, the total number of records processed (print NR “ Total Files”). Code Listing 17.4 shows the printed report.

✓ Tip

  • Remember that you could embed awk scripts in a shell script, as with the previous sed example, if it’s something you’ll use frequently.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.51.241