AWK

In this page

  1. Selecting colums from a file

1. Selecting columns from a file

Let's suppose I have a file with tabular data in 10 columns. I want to create a new file with only two columns (1 and 4), skip the first line of the original file, and set the separator as a tab. The oneliner below does that.

$ awk 'NR!=1{print $1, $4}' OFS="\t" inputfile.dat > newfile.dat

Breaking it down:

  • NR is the Number of Records. Here, I do not want the first line, hence NR!=1. Other conditionals, such as NR>3, also work.
  • print $1, $4 will print columns 1 and 4.
  • The default output separator is a space. OFS="\t" redefines the Output Field Separator as a tab.
  • The data is read from inputfile.dat and written (in linux bash at least) to the newfile.dat by the ">" redirection.