Use awk instead of cut to cut out specific columns of a file

By | 2013/01/17

For separating out specific columns of a file, try using awk!


The command to use is:

$ awk '{print $9,$10}' file.txt > file_cut.txt

Where 9 or 10 indicates the ninth or tenth column of a text file.


For an example, say you have the output of an ls -l:

drwxr-xr-x 13 root root   4096 Jun 19  2012 .
drwxr-xr-x 25 root root   4096 Dec 19 21:39 ..
drwxr-xr-x  2 root root   4096 Jan 16 07:42 backups
drwxr-xr-x 23 root root   4096 Jun 18  2012 cache
drwxr-xr-x  3 root root   4096 Jun 19  2012 games
drwxr-xr-x 83 root root   4096 Dec 20 20:44 lib
drwxrwsr-x  2 root staff  4096 Nov 13  2010 local
lrwxrwxrwx  1 root root      9 Jun 22  2011 lock -> /run/lock
drwxr-xr-x 24 root root  36864 Jan 17 19:03 log
drwxrwsr-x  2 root mail   4096 Nov 30 19:55 mail
drwxr-xr-x  2 root root   4096 Nov 23  2010 opt
lrwxrwxrwx  1 root root      4 Jun 22  2011 run -> /run
drwxr-xr-x 10 root root   4096 Sep 18 13:35 spool
drwxrwxrwt  2 root root   4096 Jan 17 19:03 tmp
drwxr-xr-x  2 root root   4096 Jun 16  2011 www

Save that as file.txt. Now use awk to cut out say, just the fourth column (group names):

$ awk '{print $4}' file.txt > file_cut.txt

You are then left with this in file_cut.txt:

root
root
root
root
root
root
staff
root
root
mail
root
root
root
root
root

I like to use this to grab the IPs only from apache logs:

$ awk '{print $1}' /var/log/apache2/access.log > ip_addresses.txt

Hack on,