Wednesday, February 24, 2010

bash: read a specific line or/and a column from a file

If we have column-row wise txt files, we can use awk and sed programs to read the rows and columns of such files.

Read specific line

To read a specific line from a txt file, the following commands can be usedawk 'NR==12' file.txt sed -n '12p' file.txt In both cases, line 12 will be returned.

Read specific column

awk '{print $1, $2}' file The code will return first and second columns from file.txt

Read specific column and line

Additionally, using awk we can get a specific column(s) in of a given line as followsawk 'NR==12 {print $1, $2}' file.txtThe Code will return first and second columns form a line no. 12.