【问题标题】:Escape CSV file with sed or other command line tool使用 sed 或其他命令行工具转义 CSV 文件
【发布时间】:2017-11-09 06:00:44
【问题描述】:

我有以下 CSV,用“|”分隔。

101|abc|this is desc|2017
102|xyz|"thie is a long desc
des for xyz continue here."|2017

我有两条记录,101102。 102 条记录分为 2 行。如何使用sed 或其他命令行工具来转义带有“/”的换行符?

【问题讨论】:

  • 预期输出是什么?
  • 换行不是记录的结尾吗?如果是这样,换行符不是 eor 的唯一原因是如果一个字段识别引号,它可以用嵌入的换行符进行扩展。 csv 解析器不能正确解释这个,或者是什么问题?

标签: regex linux csv sed command-line


【解决方案1】:

awk 是处理此问题的更好工具。

假设您知道每行需要多少列。你可以使用这个awk 命令:

awk -v n=4 -F '|' 'p+NF<n{p+=NF-1; print $0 "\\"; next} {p=0} 1' file

101|abc|this is desc|2017
102|xyz|"this is a long desc\
des for xyz continue here."|2017

【讨论】:

    【解决方案2】:

    对于您的具体情况,您可以使用它。

    $ cat lll 101|abc|this is desc|2017 102|xyz|"thie is a long desc des for xyz continue here."|2017 105|xyz|"thie is a long desc des for xyz continue here."|2017 101|abc|this is desc|2017 101|abc|this is desc|2017 101|abc|this is desc|2017 105|xyz|"thie is a long desc des for xyz continue here."|2017

    $ perl -F'\n' -ane 'BEGIN{our $line_to_join = undef; } foreach ( @F) { if (/[a-z]+$/) { $line_to_join = $_; } elsif ($line_to_join){ print $line_to_join,"/\n",$_,"\n"; $line_to_join = undef; }else{print $_,"\n" ; $line_to_join = undef;}} ;' < lll

    输出:

    101|abc|this is desc|2017 102|xyz|"thie is a long desc/ des for xyz continue here."|2017 105|xyz|"thie is a long desc/ des for xyz continue here."|2017 101|abc|this is desc|2017 101|abc|this is desc|2017 101|abc|this is desc|2017 105|xyz|"thie is a long desc/ des for xyz continue here."|2017

    【讨论】:

    • 我必须让这个通用,而不仅仅是限制在 102
    • 我现在已经使用 perl 作为解决方案,或者您可以使用下面答案中的 awk
    【解决方案3】:
    $ sed '/102/ s#$#/&#' file11
    101|abc|this is desc|2017
    102|xyz|"thie is a long desc/
    des for xyz continue here."|2017
    

    【讨论】:

      猜你喜欢
      • 2021-06-23
      • 1970-01-01
      • 1970-01-01
      • 2016-04-19
      • 2015-02-06
      • 2018-11-15
      • 1970-01-01
      • 2014-02-09
      • 1970-01-01
      相关资源
      最近更新 更多