用逗号替换行尾,并在sed/awk中插入括号

用逗号替换行尾,并在sed/awk中插入括号,awk,sed,text-processing,Awk,Sed,Text Processing,我正在尝试处理以下格式的文件内容: this1,EUR that2,USD other3,GBP this1(EUR),that2(USD),other3(GBP) 对于此格式: this1,EUR that2,USD other3,GBP this1(EUR),that2(USD),other3(GBP) 结果应该是一行 到目前为止,我已经提出了一系列运行良好的命令: cat myfile | sed -e 's/,/\(/g' | sed -e 's/$/\)/g' | tr '

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

this1,EUR 
that2,USD
other3,GBP
this1(EUR),that2(USD),other3(GBP)
对于此格式:

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
也可以帮助您完成同样的任务

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

$ awk -F, '{ printf "%s%s(%s)", c, $1, $2; 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/,([^,]*)(,?)/(\1)\2/g'
this1(EUR),that2(USD),other3(GBP)

此解决方案是超级可读的,但它基于第一个字段始终是数字的假设。我会简化这个例子,使它更一般。的确!编辑为使用字母数字第一个字段。我发现这是最简单和更可读的解决方案。您可以使用新数据来结束结果。谢谢^我要发布的答案中唯一的区别是你的
c=“,”
与我的
c=FS
相比。你能解释一下val=val?val部分是什么吗?