Linux Training : 6. awk

awk

awk is a filter and output writer. When fed lots of text it can do some amazing things.

Here is a fairly gentle introduction to awk and it's uses. A trick to keep in mind is the field separator flag -F. Set this to adapt to something other than the default space delimited fields.

awk -F ":" '{print $1, $3, $4}' < /etc/passwd

will print the username, UID and GID for all users.

(question)

  1. Print the username and default shell for each user
  2. Print the sum of all the UID values and the sum of all the GID values for all users in /etc/passwd except the nfsnobody user.

awk answers

AWK

  1. Print the username and default shell for each user
    awk -F ":" '{print $1, $7}' </etc/passwd
    root /bin/bash
    jimroot /bin/bash
    bin /sbin/nologin
    daemon /sbin/nologin
    adm /sbin/nologin
    lp /sbin/nologin
    sync /bin/sync
    shutdown /sbin/shutdown
    
    <snip extra lines>
    sabayon /sbin/nologin
    gdm /sbin/nologin
    tomcat /bin/sh
    jim /bin/bash
    jimtest /bin/bash
    
  2. Print the sum of all the UID values and the sum of all the GID values for all users in /etc/passwd except the nfsnobody user.
    awk -F ":" '{if ($3 < 10000) sumuid+=$3
        if ($4 < 10000) sumgid+=$4
        print "The sum of UID is " sumuid, " and the sum of GID is " sumgid}' < /etc/passwd | tail -n 1
    
    The sum of UID is 20233  and the sum of GID is 14297
    
    
    Since nfsnobody has a UID and GID that is far larger than 10,000, simply excluding it with a conditional "if" is easy.
    The last part tail -n 1 will only print the last (-n 1) line. It has a counter part called head that works on the top of files.

LIN:return