Tahmtan Ebrahimi
Tahmtan Ebrahimi

Reputation: 99

print first four columns but afterwards every forth column

I have a big table. I want to keep the first four columns but afterwards only print every forth column.

I tried

awk -v OFS="\t" '{
                   for(i=1;i<=NF;i++){
                        if(i<=4)
                            print $0
                         else if(i>4 && (i%4)==0)
                             print $i
                    }
}'

Upvotes: 3

Views: 102

Answers (3)

Costas
Costas

Reputation: 343

To avoid much test in script try:

awk -F, '{
printf "%s\t%s\t%s",$1,$2,$3
for(i=4;i<=NF;i+=4)
    printf "\t%s",$i
print ""
          }' file

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 203532

Borrowing @haifzhan's input file and using ;s instead of tabs in the output so you can see where the OFSs occur:

$ cat file
1,2,3,4,5,6,7,8,9,10,11,12,13
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17
1,2,3,4,5,6,7,8,9,10,11,12,13

$ cat tst.awk
BEGIN { FS=","; OFS=";" }
{
    for (i=1;i<=NF;i++) {
        if ( i<5 || !(i%4) ) {
            printf "%s%s", (i>1?OFS:""), $i
        }
    }
    print ""
}

$ awk -f tst.awk file
1;2;3;4;8;12
1;2;3;4;8;12;16
1;2;3;4;8;12

Just change the settings of FS and OFS in the BEGIN section to be your real input and desired output field separators.

Upvotes: 0

Haifeng Zhang
Haifeng Zhang

Reputation: 31895

Try this:

hzhang@dell-work ~ $ cat sample.csv 
1,2,3,4,5,6,7,8,9,10,11,12,13
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17
1,2,3,4,5,6,7,8,9,10,11,12,13
hzhang@dell-work ~ $ cat test.awk 
BEGIN{
FS=",";
OFS="\t"
}
{   
    str = "";
    counter = 0;
    for(i=1; i<=NF; i++){
        if(i <= 3 || i % 4 == 0){
            counter += 1
            if(counter < 3 + NF/4 - 1){
                str = str $i OFS
            }else{
                str = str $i
            }
        }
    };
    print str
}
hzhang@dell-work ~ $ awk -f test.awk sample.csv
1   2   3   4   8   12
1   2   3   4   8   12  16
1   2   3   4   8   12

I was using commas as field separator, if your field separator is whitespace, just remove FS that in the BEGIN clause.

Upvotes: 3

Related Questions