Tech Tip: Fun With Gawk

When grep and sed aren't enough, gawk may provide the extra horsepower that you need. The following tip contains a sampling of some of the things one might do with gawk.

Extract the last column from a text file, whitespace-separated:

cat myfile | gawk '{print $NF}'

or:

gawk '{print $NF}' myfile

List counts of files owned by each user in the current directory:

/bin/ls -l | \
    gawk 'NR > 1 {counts[$3]++;}
          END {for (s in counts) {
                   printf("  %-15s : % 5d\n",
                          s, counts[s]);}}' | \
        sort

Kill your processes (one use is to kill a hung login if you can remotely log in to the workstation from another machine):

ps -elf | \
    gawk -v me="$USER" '$3 == me {print $4}' | \
        egrep -v $$ | \
            xargs -i@@ kill -9 @@; kill -9 $$
Load Disqus comments