Monday, November 24, 2008

Print range of columns using awk - exclude range


This is more relevant when you have a file with huge number of columns and you want to print a range of columns from the file or you want to exclude a range of columns from printing and print the rest of the columns.

Lets see with an small example,

Input file:

$ cat details.txt
Name Age Sex Add DOB CARD
AXU 12 M IN 12-Jul Y
ANI 13 F IN 10-Jan N
JCK 16 M JP 03-Frb Y
LON 12 M IN 12-Oct Y

A) Print a range of columns using awk:

e.g. Print from column 2 till column 4 using awk

$ awk -v f=2 -v t=4 '{ for (i=f; i<=t;i++) printf("%s%s", $i,(i==t) ? "\n" : OFS) }' details.txt

Age Sex Add
12 M IN
13 F IN
16 M JP
12 M IN

B) Exclude column range from printing in awk:

e.g. Exclude column range 2-4 and print the rest of the columns from the above file details.txt

$ awk -v f=2 -v t=4 '
{ for (i=1; i<=NF;i++)
if( i>=f && i<=t) continue;
else
printf("%s%s", $i,(i!=NF) ? OFS : ORS) }' details.txt

Name DOB CARD
AXU 12-Jul Y
ANI 10-Jan N
JCK 03-Frb Y
LON 12-Oct Y

No comments:

© Jadu Saikia www.UNIXCL.com