Main Menu

Search

LINUX: Awk Command To Print Particular Column Or Columns From Output(How To Doc)

Awk command can be used to filter output and display particular column or columns in the output.
For e.g. if you want to print only print particular column from "ls -lrt" command below command can be used.

ls -lrt | awk {'print $n'}

In above command replace n with the column number you want to print.

For e.g. if you want to print two or more columns from ls -lrt output below command can be used.

ls -lrt | awk {'print $n1,$n2'}

In above command replace n1 and n2 with the column numbers you want to print.

In above example we use awk with "ls -lrt", but awk command can be used with any commands like cat, tar etc.

To demonstrate above command with output, for e.g. if "ls -lrt" command output is shown as follows:


drwxr-xr-x.   2 root root    6 Aug 30  2016 srv
drwxr-xr-x.   2 root root    6 Aug 30  2016 opt
drwxr-xr-x.   2 root root    6 Aug 30  2016 mnt
drwxr-xr-x.   2 root root    6 Aug 30  2016 media
drwxr-xr-x.   3 root root   16 Aug 30  2016 home

If you run below awk command to print only column 9
ls -lrt | awk {'print $9'}

Your output will only list column 9 as follows:
srv
opt
mnt
media
home

If you run below awk command to pring only columns 1 and 9



ls -lrt | awk {'print $1,$9'}

your output will look as follows:

drwxr-xr-x. srv
drwxr-xr-x. opt
drwxr-xr-x. mnt
drwxr-xr-x. media
drwxr-xr-x. home


Products to which Article Applies


All Linux environments

Additional References

https://www.geeksforgeeks.org/awk-command-unixlinux-examples/

No comments:

Post a Comment