【问题标题】:Add quotation marks to each var in a txt file [duplicate]为txt文件中的每个var添加引号[重复]
【发布时间】:2020-02-05 03:03:39
【问题描述】:

类似于这个问题here,我想在一个没有空格的文件中用逗号分隔每个变量(有时是字符串,有时是数字),如下所示:

variable1,12345,variable2,AA3

使用 BASH(在 macOS 10.14.6 上)为每个单词添加引号的最简单方法是什么?

最终结果应如下所示:

"variable1","12345","variable2","AA3"

【问题讨论】:

  • 为什么不使用链接问题的任何答案?
  • 因为我不知道“sed”或类似的东西来对我的具体情况进行必要的调整(逗号之间没有空格)。

标签: bash macos


【解决方案1】:

您可以使用 'sed' 在行首、行尾插入 '"',并替换每个 '.'用'","'。

sed -e 's/^/"/' -e 's/$/"/' -e 's/,/","/g'

【讨论】:

    【解决方案2】:

    使用单个sed 命令:

    s='variable1,12345,variable2,AA3'
    sed -E 's/[^,]+/"&"/g' <<< "$s"
    

    "variable1","12345","variable2","AA3"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-02
      • 1970-01-01
      相关资源
      最近更新 更多