Ankit Ramani
Ankit Ramani

Reputation: 76

Add comma after each word

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

Upvotes: 4

Views: 14495

Answers (4)

Sadhun
Sadhun

Reputation: 264

A normal sed gave me the expected output,

sed 's/ /, /g' filename

Upvotes: 4

Wintermute
Wintermute

Reputation: 44043

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

Upvotes: 5

Jadi
Jadi

Reputation: 739

You can use awk for this purpose. Loop using for and add a , after any char except on the last occurance (when i == NF).

$ echo $document_keywords | awk '{for(i=1;i<NF;i++)if(i!=NF){$i=$i","}  }1'

Upvotes: 4

anubhava
anubhava

Reputation: 785186

Using BASH string substitution:

document_keywords='Latex document starter CrypoServer'
echo "${document_keywords//[[:blank:]]/,}"
Latex,document,starter,CrypoServer

Or sed:

echo "$document_keywords" | sed 's/[[:blank:]]/,/g'
Latex,document,starter,CrypoServer

Or tr:

echo "$document_keywords" | tr '[[:blank:]]/' ','
Latex,document,starter,CrypoServer

Upvotes: 2

Related Questions