Print the first four columns, but then every fourth column
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
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
source to share