We often need to extract a few columns of useful data from a file. For example, in a list of students ordered by their scores, we want to get the fourth highest scorer. This recipe shows how to do this.
Printing the nth word or column in a file or line
How to do it...
The awk command is frequently used for this task.
- To print the fifth column, use the following command:
$ awk '{ print $5 }' filename
- We can print multiple columns and insert a custom string between the columns.
The following command will print the permission and filename of each file in the current directory:
$ ls -l | awk '{ print $1 " : " $8 }' -rw-r--r-- : delimited_data.txt -rw-r--r-- : obfuscated.txt -rw...