【问题标题】:Inserting quotes to pipe separated line using sed使用 sed 将引号插入管道分隔线
【发布时间】:2012-09-19 12:03:34
【问题描述】:

我有一个定制的工具,它使用 SAX 解析 XML 文件并将它们再现为管道分隔值,行的示例是:

name|lastname|address|telephone|age|other info|other info

我想重写每一行,我会使用 bash 脚本来完成,但我遇到了一些困难。 基本上我想在引号之间设置每个单词,上面一行的一个例子是:

"name"|"lastname"|"address"|"telephone"|"age"|"other info"|"other info"

我正在尝试使用 sed 来做这件事,并且我在这个 sed 行上取得了部分成功

sed 's:|:"|":g'

当我得到输出时: 姓名"|"姓氏"|"地址"|"电话"|"年龄"|"其他信息"|"其他信息

但我不知道如何为第一个字符和最后一个字符设置引号, 有什么建议吗?

【问题讨论】:

  • 如果任何字段包含双引号怎么办?

标签: bash sed


【解决方案1】:

你绝对是在正确的轨道上,这里是如何覆盖行首,行尾的特殊情况:

 sed 's:|:"|":g;s/^/"/;s/$/"/'

^ char 锚点搜索到行首,$ char 锚点搜索到行尾。

IHTH

【讨论】:

    【解决方案2】:
    line='name|lastname|address|telephone|age|other info|other info'
    
    echo $line| sed -e 's/|/"|"/g' -e 's/^/"/' -e 's/$/"/'
    

    给予:

    "name"|"lastname"|"address"|"telephone"|"age"|"other info"|"other info"
    

    【讨论】:

      【解决方案3】:

      一种使用GNU awk的方式:

      awk 'BEGIN { FS=OFS="|"; Q="\"" } { for (i=1; i<=NF; i++) $i = Q $i Q }1'
      

      结果:

      "name"|"lastname"|"address"|"telephone"|"age"|"other info"|"other info"
      

      【讨论】:

      • 可以简单一点:{for (i=1; i&lt;=NF; i++) $i = Q $i Q; print}
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 2016-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多