Printing the nth word on each line using awk

There are many ways in the linux terminal to print the nth word of a given file or output. One way to do this without worrying about tabs, extra spaces or word length is to use awk. With awk, this can be done on one line by using the {print $<n>} syntax.

For example, the ps command may print this:

$ ps
  PID TTY          TIME CMD
 3677 pts/1    00:00:00 bash
 3699 pts/1    00:00:00 ps
 3700 pts/1    00:00:00 awk

To print only the fourth column (CMD), we can pipe the output to awk like so:

$ ps | awk '{print $4}'

Leave a Reply

Your email address will not be published.