[英]Add comma after each word
I have a variable (called $document_keywords) with following text in it:我有一个变量(称为 $document_keywords),其中包含以下文本:
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问候, Ankit
In order to preserve whitespaces as they are given, I would use sed like this:为了保留给定的空格,我会像这样使用 sed:
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
一个普通的 sed 给了我预期的输出,
sed 's/ /, /g' filename
You can use awk
for this purpose.为此,您可以使用awk
。 Loop using for
and add a ,
after any char except on the last occurance (when i == NF).使用for
循环并在除最后一次出现(当 i == NF 时)之外的任何字符,
添加 a 。
$ echo $document_keywords | awk '{for(i=1;i<NF;i++)if(i!=NF){$i=$i","} }1'
Using BASH string substitution:使用 BASH 字符串替换:
document_keywords='Latex document starter CrypoServer'
echo "${document_keywords//[[:blank:]]/,}"
Latex,document,starter,CrypoServer
Or sed
:或sed
:
echo "$document_keywords" | sed 's/[[:blank:]]/,/g'
Latex,document,starter,CrypoServer
Or tr
:或tr
:
echo "$document_keywords" | tr '[[:blank:]]/' ','
Latex,document,starter,CrypoServer
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.