用逗号替换行尾并将括号放在 sed/awk

Replace end of line with comma and put parenthesis in sed/awk

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

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([=13=], 0, length([=13=])- 1)}'

是否有更简单的方法仅通过 awk 命令来完成相同的操作?

以下 awk 可能会对您有所帮助。

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

另一个awk:

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

1(欧元),2(美元),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

使用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/,([^,]*)(,?)/()/g'
this1(EUR),that2(USD),other3(GBP)