Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add comma after each word

Tags:

linux

shell

sed

I have a variable (called $document_keywords) with following text in it:

Latex document starter CrypoServer

I want to add comma after each word, not after last word. So, output will become like this:

Latex, document, starter, CrypoServer

Anybody help me to achieve above output.

regards, Ankit

like image 925
Ankit Ramani Avatar asked Dec 12 '22 00:12

Ankit Ramani


2 Answers

In order to preserve whitespaces as they are given, I would use sed like this:

echo "$document_keywords" | sed 's/\>/,/g;s/,$//'

This works as follows:

s/\>/,/g   # replace all ending word boundaries with a comma -- that is,
           # append a comma to every word
s/,$//     # then remove the last, unwanted one at the end.

Then:

$ echo 'Latex document starter CrypoServer' | sed 's/\>/,/g;s/,$//'
Latex, document, starter, CrypoServer
$ echo 'Latex   document starter CrypoServer' | sed 's/\>/,/g;s/,$//'
Latex,   document, starter, CrypoServer
like image 198
Wintermute Avatar answered Jan 03 '23 12:01

Wintermute


A normal sed gave me the expected output,

sed 's/ /, /g' filename
like image 36
Sadhun Avatar answered Jan 03 '23 13:01

Sadhun