将两个csv行合并为一行

时间:2015-11-08 14:32:16

标签: python csv awk

我正在尝试将两行csv文件合并为一行。

csv文件:

"Operations=5009.0,AverageLatency(us)=714.4248352964663,MinLatency(us)=300.0,MaxLatency(us)=173567.0,95thPercentileLatency(us)=1216.0,99thPercentileLatency(us)=2645.0,Return=5009"
"Operations=4991.0,AverageLatency(us)=831.4189541174113,MinLatency(us)=370.0,MaxLatency(us)=25999.0,95thPercentileLatency(us)=1495.0,99thPercentileLatency(us)=2857.0,Return=4991"

预期产出:

"Operations=5009.0,AverageLatency(us)=714.4248352964663,MinLatency(us)=300.0,MaxLatency(us)=173567.0,95thPercentileLatency(us)=1216.0,99thPercentileLatency(us)=2645.0,Return=5009","Operations=4991.0,AverageLatency(us)=831.4189541174113,MinLatency(us)=370.0,MaxLatency(us)=25999.0,95thPercentileLatency(us)=1495.0,99thPercentileLatency(us)=2857.0,Return=4991"

我试过了:

awk 'NR%2{printf $0" ";next;}1' file.csv

但它不会打印整个第一行。

"Operations=5009.0,AverageLatency(us)=714.4248352964663,MinLatency(us)=300.0,MaxLatency(us)=173567.0,95thPercentileLatency(us)=1216.0,99thPercenti "Operations=4991.0,AverageLatency(us)=831.4189541174113,MinLatency(us)=370.0,MaxLatency(us)=25999.0,95thPercentileLatency(us)=1495.0,99thPercentileLatency(us)=2857.0,Return=4991"

有什么想法吗?

由于

1 个答案:

答案 0 :(得分:1)

对于您描述的示例,以下代码应该完成这项工作:

awk 'BEGIN{OFS=","}{if(NR%2==1){val=$0;}else{print val,$0}}' inputFile

将奇数行的内容存储在变量中,并将该变量的内容与偶数行中的当前行一起打印。

输出:

"Operations=5009.0,AverageLatency(us)=714.4248352964663,MinLatency(us)=300.0,MaxLatency(us)=173567.0,95thPercentileLatency(us)=1216.0,99thPercentileLatency(us)=2645.0,Return=5009","Operations=4991.0,AverageLatency(us)=831.4189541174113,MinLatency(us)=370.0,MaxLatency(us)=25999.0,95thPercentileLatency(us)=1495.0,99thPercentileLatency(us)=2857.0,Return=4991"

如果输入文件中只有两行,则有一种更复杂的方法可以解决问题(我首先想到的):

awk 'BEGIN{RS=""; FS="\n"; OFS=",";}{print $1,$2;}' inputFile

此代码将换行符(“\ n”)解释为字段分隔符。也就是说,inputFile中的两行显示为同一数据集的两列。 (我们需要RS=""来覆盖其默认值。)
在输出中,此换行符必须替换为逗号(OFS=",")。