How to Replace Spaces with Commas in the Linux Console (sed, tr, awk)

Category: Servers & Websites
Posted: October 5, 2019
Author: Antonio

Processing logs and other text data is handy with scripts right in the Linux console. With sed, awk and regular expressions you can almost work miracles :-) A common task is to replace spaces with commas, for example to turn a line into CSV.

How to Replace Spaces with Commas in the Linux Console (sed, tr, awk)

In short: sed 's/ /,/g' file replaces all spaces with commas. Without g only the first space on each line is replaced.

Replace the first space

sed 's/\s/,/' test.txt
red,blue green black

\s matches any whitespace character (a space or a tab).

Replace all spaces

Add the g (global) flag:

sed 's/\s/,/g' test.txt
red,blue,green,black

Several spaces in a row — one comma

If words are sometimes separated by two or three spaces or tabs, replace the whole group at once:

sed -E 's/\s+/,/g' test.txt

Other ways

  • tr ' ' ',' < test.txt — the simplest way to replace each space with a comma;
  • awk -v OFS=',' '{$1=$1; print}' test.txt — replaces any runs of spaces with a comma and trims spaces at the start and end of the line;
  • sed -i 's/ /,/g' test.txt — edits the file itself (without -i the result is only printed). Make a copy of the file before using -i.

That simple!

Related posts:

Leave a Comment

Copying content from this site is allowed only with a direct link to the source - https://nemcd.com