Add a comma to every column value in a table [unix]

I have a file produced from a program that is filled with values as such :

1 [4:space] 2 [4:space] 3 [4:space] ... N

There is 4 space between each values, I want to remove the 3 spaces and place commas after each values to get the final results :

1, 2, 3, ..., N

I found out from other topics that this command can remove the 3 spaces :

awk -F'  +' -v OFS='\t' '{sub(/ +$/,""); $1=$1}1' file

I need to add commas then, or maybe is there a way to removes the space and add commas at the same time.

>Solution :

To replace all space with comma and a space, use:

$ awk '{gsub(/ +/,", ")}1' file
1, 2, 3, ..., N

To replace exactly three spaces with a comma, use:

$ awk '{gsub(/ {3}/,",")}1' file

Using field delimiters for it:

$ awk -F"    " -v OFS=", " '{$1=$1}1' file

Leave a Reply