【问题标题】:Replace end of line with comma and put parenthesis in sed/awk用逗号替换行尾并将括号放入 sed/awk
【发布时间】:2018-09-20 03:51:34
【问题描述】:

我正在尝试以这种格式处理文件的内容:

this1,EUR 
that2,USD
other3,GBP

转成这种格式:

this1(EUR),that2(USD),other3(GBP)

结果应该是一行。

到目前为止,我已经想出了这个运行良好的命令电路:

cat myfile | sed -e 's/,/\(/g' | sed -e 's/$/\)/g' | tr '\n' , | awk '{print substr($0, 0, length($0)- 1)}'

有没有更简单的方法来做同样的事情,只需要一个 awk 命令?

【问题讨论】:

    标签: awk sed text-processing


    【解决方案1】:

    关注awk 可能对您有所帮助。

    awk -F, '{val=val?val OFS $1"("$2")":$1"("$2")"} END{print val}' OFS=,  Input_file
    

    【讨论】:

    • 能否请您解释一下 val=val?val 部分是什么?
    【解决方案2】:

    另一个 awk:

    $ awk -F, '{ printf "%s%s(%s)", c, $1, $2; c = ","} END { print ""}' file
    

    1(欧元)、2(美元)、3(英镑)

    【讨论】:

    • 这个解决方案可读性很强,但它基于第一个字段始终是数字的假设。我将修改示例以使其更通用。
    • 确实!编辑为使用字母数字第一个字段。
    • 我发现这是最简单且更具可读性的解决方案。您可以使用新数据修改结果。谢谢!
    • ^1 我要发布的答案的唯一区别是您的c = "," 与我的c=FS
    【解决方案3】:

    玩弄分隔符和gsub:

    $ awk 'BEGIN{RS="";ORS=")\n"}{gsub(/,/,"(");gsub(/\n/,"),")}1' file
    this1(EUR),that2(USD),other3(GBP)
    

    解释:

    $ awk '
    BEGIN {
        RS=""            # record ends in an empty line, not newline
        ORS=")\n"        # the last )
    }
    {
        gsub(/,/,"(")    # replace commas with (
        gsub(/\n/,"),")  # and newlines with ),
    }1' file             # output
    

    【讨论】:

      【解决方案4】:

      使用paste+sed

      $ # paste -s will combine all input lines to single line
      $ seq 3 | paste -sd,
      1,2,3
      
      $ paste -sd, ip.txt
      this1,EUR,that2,USD,other3,GBP
      $ # post processing to get desired format
      $ paste -sd, ip.txt | sed -E 's/,([^,]*)(,?)/(\1)\2/g'
      this1(EUR),that2(USD),other3(GBP)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-05-29
        • 1970-01-01
        • 2019-05-02
        • 2016-11-25
        • 2012-03-01
        • 2017-06-25
        • 1970-01-01
        相关资源
        最近更新 更多