Replace whitespace with a comma in a text file in Linux

aye picture aye · Aug 13, 2009 · Viewed 198.9k times · Source

I need to edit a few text files (an output from sar) and convert them into CSV files.

I need to change every whitespace (maybe it's a tab between the numbers in the output) using sed or awk functions (an easy shell script in Linux).

Can anyone help me? Every command I used didn't change the file at all; I tried gsub.

Answer

Alberto Zaccagni picture Alberto Zaccagni · Aug 13, 2009
tr ' ' ',' <input >output 

Substitutes each space with a comma, if you need you can make a pass with the -s flag (squeeze repeats), that replaces each input sequence of a repeated character that is listed in SET1 (the blank space) with a single occurrence of that character.

Use of squeeze repeats used to after substitute tabs:

tr -s '\t' <input | tr '\t' ',' >output