Printing the nth word or column in a file or line
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.
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-r--r-- : paste1.txt -rw-r--r-- : paste2.txt
See also
- The Using awk for advanced text processing recipe in this chapter explains the
awk
command - The Cutting a file column-wise with cut recipe in this chapter explains how to extract data from text files