【问题标题】:awk or sed etc replace comma with | but where between quotesawk 或 sed 等用 | 替换逗号但是引号之间的位置
【发布时间】:2019-05-02 19:13:16
【问题描述】:

我有一个分隔文件,我试图用一个或栏替换逗号 |逗号(和其他文本)在引号 (") 之间的情况除外

我知道我可以使用 sed 's/,/|/g' 文件名替换逗号,但我不确定如何将引号之间的文本作为规则的例外。或者如果它甚至可以这么容易。

【问题讨论】:

  • 我猜您正在尝试“修复”一个在包含逗号的字段周围使用引号的 CSV 文件。如果是这样,我建议您使用支持 CSV 的脚本语言,例如python + csv 模块。
  • 请在您的问题中提供示例输入和输出。
  • 或者将|设置为字段分隔符重新导出您的数据。或查看csv 特定工具。这里一直提到几个。您是否尝试搜索此主题?祝你好运。
  • 其实用 perl 很简单,但是你需要知道 " 是如何在双引号子串中转义的。
  • 看看 GNU awk 和 FPAT

标签: awk sed replace


【解决方案1】:

正如这里的人所建议的那样,最好和最安全的方法是将 csv 读取为带有适当模块/库的 csv。

无论如何,如果你想在这里 sed 它是:

sed -i 's/|//g;y/,/|/;:r;s/\("[^"]*\)|\([^"]*"\)/\1,\2/g;tr' file.csv

程序:

  • 首先,它会从 csv 中删除所有管道,以免损坏 csv。
  • 其次,它将所有逗号转换为管道
  • 第三,它递归地将所有引用的管道“恢复”为逗号。

测试:

$ cat file.csv
aaa,1,"what's up"
bbb,2,"this is pipe | in text"
ccc,3,"here is comma, in text"
ddd,4,  ",, here a,r,e multi, commas,, ,,"
"e,e",5,first column

$ cat file.csv | sed 's/|//g;y/,/|/;:r;s/\("[^"]*\)|\([^"]*"\)/\1,\2/g;tr'
aaa|1|"what's up"
bbb|2|"this is pipe  in text"
ccc|3|"here is comma, in text"
ddd|4|  ",, here a,r,e multi, commas,, ,,"
"e,e"|5|first column

$ cat file.csv | sed 's/|//g;y/,/|/;:r;s/\("[^"]*\)|\([^"]*"\)/\1,\2/g;tr' | awk -F'|' '{ print NF }'
3
3
3
3
3

【讨论】:

    【解决方案2】:

    你可以试试这个 sed:

    sed ':A;s/\([^"]*"[^"]*"\)\([^"]*\)\(,\)/\1|/;tA' infile
    

    【讨论】:

      【解决方案3】:

      使用 GNU awk、FPAT 和 @Kubator 的示例文件:

      $ awk '
      BEGIN {
          FPAT="([^,]+)|( *\"[^\"]+\" *)"  # define the field pattern, notice the space before "
          OFS="|"                          # output file separator
      }
      {
          $1=$1                            # rebuild the record
      }1' file                             # output
      aaa|1|"what's up"
      bbb|2|"this is pipe | in text"
      ccc|3|"here is comma, in text"
      ddd|4|  ",, here a,r,e multi, commas,, ,,"
      "e,e"|5|first column
      

      【讨论】:

        猜你喜欢
        • 2020-02-20
        • 2014-03-24
        • 1970-01-01
        • 2014-10-31
        • 2018-09-20
        • 1970-01-01
        • 2015-10-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多