Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash insert a comma (,) after every third field of a variable or array?

Tags:

arrays

bash

sed

awk

I have a variable with the following contents: "a b c d e f g h i j k l", how would you go about adding a comma sign (,) after each third member so it looks like this: "a b c, d e f, g h i, j k l".

Initially all my variable data is stored in an array so if anyone knows how to directly manipulate the array, it would be great.

Thanks in advance

like image 535
f10bit Avatar asked Nov 20 '25 09:11

f10bit


1 Answers

awk

$ echo "a b c d e f g h i j k l" | awk '{for(i=1;i<NF;i++)if(i%3==0){$i=$i","}  }1'
a b c, d e f, g h i, j k l
like image 103
ghostdog74 Avatar answered Nov 21 '25 22:11

ghostdog74



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!