Add quotation marks to each word in a file

孤街浪徒 提交于 2020-03-28 04:18:51

问题


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?

The end result should look like:

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

回答1:


Simply with sed:

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

The output:

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



回答2:


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.



来源:https://stackoverflow.com/questions/48152407/add-quotation-marks-to-each-word-in-a-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!