How to use ‘awk’ to print columns from a text file (in any order)

Printing columns of information from Unix text files is easy, especially using commands like awk, perl, and more recently, ruby. This short tutorial shows my old-school awk way of doing this.

awk column printing examples

Suppose you have a file named foo with contents like this:

1 2 3
a b c

You can easily use awk to print columns of information from this file. Here are a few examples that show how to print the data columns from the file:

$ cat foo
1 2 3
a b c

$ awk '{ print $1 }' foo
1
a

$ awk '{ print $2 }' foo
2
b

$ awk '{ print $3 }' foo
3
c

$ awk '{ print $1, $3 }' foo
1 3
a c

$ awk '{ print $3, $1 }' foo
3 1
c a

As you can see, with awk you can print any column you want, and can print the columns in any order you want.

While all of these examples show awk working directly on a file, it can also read its input from a Unix pipeline, like this:

$ cat foo | awk '{ print $3, $1 }'
3 1
c a

awk is a great tool for rearranging columns in Unix text file output, but if for some reason it doesn’t do what you need, here’s a link that shows a powerful method of column oriented data extraction with Perl.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.