Print the first four columns, but then every fourth column
I have a large table. I want to keep the first four columns, but then only print every fourth 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
                    }
}'
      
        
        
        
      
     
+3 
Tahmtan Ebrahimi 
source
to share
      
3 answers
      
        
        
        
      
    
Try the following:
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 used commas as field separator, if your field separator is a space, just remove FS, which is in the BEGIN clause.
+3 
haifzhan 
source
to share
      Borrowing @ haifzhan's input file and using ;
      
        
        
        
      
    tabs instead of output so you can see where OFS is happening:
$ 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 FS and OFS settings in the BEGIN section to be your actual input and desired output field delimiters.
0 
Ed morton 
source
to share
      To avoid a lot of tests in a 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
      
        
        
        
      
     
0 
Costas 
source
to share