简体   繁体   English

给文件中的每个单词加上引号

[英]Add quotation marks to each word in a file

I have some words separated by commas in a file, such as below: 我在文件中有一些用逗号分隔的单词,如下所示:

variable1, variable2, variable3, variable4

What's the easiest way to use BASH for adding quotation marks to each word? 使用BASH为每个单词加上引号的最简单方法是什么?

The end result should look like: 最终结果应如下所示:

"variable1", "variable2", "variable3", "variable4"

It can be done with parameter expansion 可以通过参数扩展来完成

str="variable1, variable2, variable3, variable4"
str2=\""${str//, /\", \"}"\"

echo "$str2"

however to have a csv format, double quotes should be just before the comma without space, the reason of double quotes may be to allow , inside a field but if field already contains a comma the quoting must be done before. 然而,有一个csv格式,双引号应该只是没有空间逗号之前,双引号的原因可能是允许,一个字段内,但如果字段中已包含一个逗号的报价前必须完成。

Simply with sed : 只需使用sed

sed 's/[^[:space:],]\+/"&"/g' file

The output: 输出:

"variable1", "variable2", "variable3", "variable4"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM