HowTo: Read a File Line By Line Using awk

How do I read a file line by line using awk utility under Unix / Linux operating systems?

awk is pattern scanning and text processing language. It is useful for manipulation of data files, text retrieval and processing, and for prototyping and experimenting with algorithms. The name AWK is derived from the surnames of its authors — Alfred Aho, Peter Weinberger, and Brian Kernighan.

By default it process one line at a time. For example following command will simply process one line at a time:
$ cat /etc/passwd | awk '{ print $0}'
Or better try
$ awk '{ print $0}' /etc/passwd

The print command is used to output text. $0 is field name for entire line. By default white space (blank line) act as field separator. You can set new field separator with -F option. For example, to use : as a field separator, enter:
$ awk -F':' '{ print $1 }' /etc/passwd

Above command will print all username using the first field ($1) for current line. You can print username ($1), shell ($7) and login home dir ($6) report as follows:
$ awk -F':' '{ print "User " $1 " login using " $7 " shell with as " $6 " home dir"}' /etc/passwd
Output:

User root login using /bin/bash shell with as /root home dir
User daemon login using /bin/sh shell with as /usr/sbin home dir
User bin login using /bin/sh shell with as /bin home dir
User sys login using /bin/sh shell with as /dev home dir
....
....
User gdm login using /bin/false shell with as /var/lib/gdm home dir
User vivek login using /bin/bash shell with as /home/vivek home dir
User sshd login using /usr/sbin/nologin shell with as /var/run/sshd home dir

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.