mardi 19 juin 2018

Inserting delimiters (comma) in space separated file every n columns using awk

I'm trying to insert two commas in between columns of multiples of 2. For example, for the following input file, I'm trying to print 2 commas in between columns b and c & d and e:-

a b c d e
f g h i j
k l m n o

The output should look something like this:-

a b , , c d , , e

The following code is what I have so far. Note that I also have pattern matching, hence the /a/. I used a for loop to print the commas with an if statement that's supposed to print two commas every two columns, which is what the modulo is for:- :-

awk '/a/{for (i = 1; i <= NF; i++) printf $i" "; if ((i%2)==0) printf " , ,"}' test.txt > blabla.txt

The results are as below. My for loop and pattern matching works just fine but for some reason, the if statement isn't being executed and I can't figure out why:-

a b c d e , ,

Any help or better alternatives would be greatly appreciated. Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire