【问题标题】:sed - remove quotes within quotes in large csv filessed - 删除大型 csv 文件中引号内的引号
【发布时间】:2012-11-22 10:56:30
【问题描述】:

我正在使用流编辑器 sed 将大量文本文件数据 (400MB) 转换为 csv 格式。

我已经接近完成,但突出的问题是引号内的引号,在这样的数据上:

1,word1,"description for word1","another text",""text contains "double quotes" some more text"
2,word2,"description for word2","another text","text may not contain double quotes, but may contain commas ,"
3,word3,"description for "word3"","another text","more text and more"

想要的输出是:

1,word1,"description for word1","another text","text contains double quotes some more text"
2,word2,"description for word2","another text","text may not contain double quotes, but may contain commas ,"
3,word3,"description for word3","another text","more text and more"

我已经四处寻找帮助,但我并没有太接近解决方案,我尝试了以下带有正则表达式模式的 sed:

sed -i 's/(?<!^\s*|,)""(?!,""|\s*$)//g' *.txt
sed -i 's/(?<=[^,])"(?=[^,])//g' *.txt

这些来自以下问题,但似乎不适用于 sed:

Related question for perl

Related question for SISS

原始文件是 *.txt,我正在尝试使用 sed 编辑它们。

【问题讨论】:

    标签: regex csv sed


    【解决方案1】:

    这是使用GNU awkFPAT 变量的一种方法:

    gawk 'BEGIN { FPAT="([^,]+)|(\"[^\"]+\")"; OFS=","; N="\"" } { for (i=1;i<=NF;i++) if ($i ~ /^\".*\"$/) { gsub(/\"/,"", $i); $i=N $i N } }1' file
    

    结果:

    1,word1,"description for word1","another text","text contains double
    quotes some more text" 2,word2,"description for word2","another
    text","text may not contain double quotes, but may contain commas ,"
    3,word3,"description for word3","another text","more text and more"
    

    解释:

    使用 FPAT,字段被定义为“任何不是 逗号”或“双引号,任何不是双引号的内容,以及 关闭双引号”。然后在输入的每一行上,循环遍历每个 字段,如果该字段以双引号开头和结尾,则删除所有 来自该领域的报价。最后,在周围添加双引号 字段。

    【讨论】:

    • @alinsoar,谢谢你们。最后,即使没有 sed,史蒂夫的回答也帮助我完成了更好的结果。
    • 此解决方案不适用于 Mac OSX Shell (Sierra)
    • @RiccardoDonato:您使用的是gawk(GNU AWK)吗? FPATgawk 特定的。
    • @Steve 对不起,你是对的!我使用的是 awk,我安装了 gawk,现在它运行良好。
    【解决方案2】:
    sed -e ':r s:["]\([^",]*\)["]\([^",]*\)["]\([^",]*\)["]:"\1\2\3":; tr' FILE
    

    这会查看"STR1 "STR2" STR3 " 类型的字符串并将它们转换为"STR1 STR2 STR3"。如果它发现了什么,它会重复,以确保它消除深度 > 2 的所有嵌套字符串。

    它还确保没有一个 STRx 包含comma

    【讨论】:

    • 谢谢,差不多了,不过我在第一行得到了1,word1,"description for word1","another text","text contains double quotes" some more text"。您还介意解释一下 \1\2\3 的作用吗?
    猜你喜欢
    • 2023-04-01
    • 2014-05-29
    • 2018-07-27
    • 2014-05-05
    • 1970-01-01
    • 2012-08-14
    • 1970-01-01
    • 2011-05-14
    • 1970-01-01
    相关资源
    最近更新 更多