programming

How do I print specific fields of a file?

To print the last field in a file called testfile, you would use the awk command like this:

awk ‘{print $NF}’ testfile

If you wanted to print fields 1 and 3 in a colon delimited file like the Unix /etc/passwd, you coud use this command:

awk -F”:” ‘{print $1, $3}’ /etc/passwd

You can also make it print a little bit cleaner by setting the column width:

awk -F”:” ‘{printf (“%-10s %-40s\n”), $1, $3}’ /etc/passwd

You can also search and print specific lines:

awk ‘/^foo/{print $1, $2}’ /path/to/file

The command above will search for lines that begin with foo and then print fields 1 and 2.

Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *

To Top