Thursday, August 8, 2013

Gawk Notes - Simple


... In which I use gawk (awk) to manipulate delineated output into a format more appropriate to my task and filter data unnecessary to me at the moment.

I'll break down the following example:
dpkg -l |awk '{ print $2 }'
The "|" is known as a "pipe".  Two separate programs are being executed and the output of the first is being "piped" into the input of the second.  This feature is so useful to so many people, it might be considered one of the most frequently used programs in userspace.

The first command:
dpkg -l 
yields:
............

ii  ffmpeg                                6:0.10.2-dmo1                      audio/video encoder, streaming server & audio/video file conv
erter.
ii  file                                  5.11-1                             Determines file type using "magic" numbers
ii  findutils                             4.4.2-4                            utilities for finding files--find, xargs
ii  firebird2.5-common                    2.5.2~svn+54376.ds4-2              common files for firebird 2.5 servers and clients
ii  firebird2.5-common-doc                2.5.2~svn+54376.ds4-2              copyright, licnesing and changelogs of firebird2.5
ii  firmware-atheros                      0.35                               Binary firmware for Atheros wireless cards
ii  firmware-b43-installer                1:015-14                           Installer package for firmware for the b43 driver
ii  firmware-bnx2                         0.35                               Binary firmware for Broadcom NetXtremeII
ii  firmware-brcm80211                    0.35                               Binary firmware for Broadcom 802.11 wireless cards
ii  firmware-intelwimax                   0.35                               Binary firmware for Intel WiMAX Connection
ii  firmware-iwlwifi                      0.35                               Binary firmware for Intel Wireless 3945, 4965 and 5000-series
 cards
ii  firmware-libertas                     0.35                               Binary firmware for Marvell Libertas 8xxx wireless
..........

The second command:
dpkg -l |awk '{ print $2 }'
Passing the output of "dpkg -l" through "awk '{ print $2 }' ", the second column (thus $2) of our first output is selected, leaving a more script- and backup-friendly list of Debian packages like this:
..........

ffmpeg
file
findutils
firebird2.5-common
firebird2.5-common-doc
firmware-atheros
firmware-b43-installer
firmware-bnx2
firmware-brcm80211
firmware-intelwimax
firmware-iwlwifi
firmware-libertas
............

Voila!

P.S.  This command can also be nested inside other commands/scripts (very simple example):

echo $(dpkg -l | grep ii | awk '{ print $2 }')  >> Installed\ Packages.txt

Brought to you by......

No comments: