Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print every nth column of a file

Tags:

awk

I have a rather big file with 255 coma separated columns and I need to print out every third column only.

I was trying something like this

awk '{ for (i=0;i<=NF;i+=3) print $i }' file

but that doesn't seem to be the solution, since it prints to only one long column. Anybody can help? Thanks

like image 564
janapka Avatar asked Dec 19 '22 17:12

janapka


1 Answers

Here is one way to do this.

The script prog.awk:

BEGIN {FS = ","} # field separator
{for (i = 1; i <= NF; i += 3) printf ("%s%c", $i, i + 3 <= NF ? "," : "\n");}

Invocation:

awk -f prog.awk <input.csv >output.csv

Example input.csv:

1,2,3,4,5,6,7,8,9,10
11,12,13,14,15,16,17,18,19,20

Example output.csv:

1,4,7,10
11,14,17,20
like image 135
Gassa Avatar answered Dec 29 '22 14:12

Gassa