Add comma after each word
11,111
Solution 1
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
Solution 2
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'
Solution 3
A normal sed gave me the expected output,
sed 's/ /, /g' filename
Solution 4
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
Author by
Ankit Ramani
Doing master in Informatik at RWTH Aachen, Germany. I completed my bachelor in Computer Engineering.
Updated on June 04, 2022Comments
-
Ankit Ramani almost 2 years
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