我的输入文件如下:
apple 6
banana 7
goat 8
我需要输出为
{6,apple},
{7,banana},
{8,goat}
但是,当我按如下所示运行awk时,它正在打印多余的最后一个逗号(,)。如何避免最后一个逗号?
awk '{print "{"$2","$1"},"}' data
{6,apple},
{7,banana},
{8,goat},
更新:
实际上,我需要这样的输出
{6,apple},
{7,banana},
{8,goat}
]
当我跑步
awk '{print "{"$2","$1"},"}' END {print "\t\t]\n}' data
它给了我
{6,apple},
{7,banana},
{8,goat},
]
我不需要最后一个逗号...在这种情况下如何避免?
答案 0 :(得分:2)
如何使用以下命令行将其管道传输到sed
?
awk ... | sed '$ s/,$//'
答案 1 :(得分:2)
使用printf
并延迟打印逗号:
$ awk '{printf "%s{%s,%s}",(NR==1?"":"," ORS),$2,$1} END{print ORS "]"}' file
{6,apple},
{7,banana},
{8,goat}
]
答案 2 :(得分:1)
这是另一种选择
$ awk 'NR==FNR{n=NR; next} {print "{" $2 "," $1 "}" (FNR==n?"\n]":",")}' file{,}
{6,apple},
{7,banana},
{8,goat}
]
答案 3 :(得分:1)
只需延迟输出:
awk 'NR>1{print lastline} {lastline="{" $2 "," $1 "},"; } END{print substr(lastline, 1, length(lastline)-1)}' data
每行打印最后一行的输出,在最后一个逗号末尾打印并打印。
答案 4 :(得分:1)
Form Responses 9
答案 5 :(得分:0)
这是Perl解决方案
/tmp> cat media.txt
apple 6
banana 7
goat 8
/tmp> perl -lne ' s/(\S+) (\d+)/{$2,$1}/g; if(eof) { print "$_\n]" } else { print "$_," } ' media.txt
{6,apple},
{7,banana},
{8,goat}
]
/tmp>
或
$ perl -lne ' s/(\S+) (\d+)/{$2,$1}/g; print eof ? "$_\n]" : "$_," ' media.txt
{6,apple},
{7,banana},
{8,goat}
]
如果文件可以容纳到内存中,则下面的Perl解决方案将起作用
/tmp> perl -0777 -ne ' s/(\S+) (\d+)/{$2,$1}/g ; print join(",\n",split)."\n]\n" ' media.txt
{6,apple},
{7,banana},
{8,goat}
]
/tmp>