多行到单行

Mulitiple rows to single line

输入 姓名 Rico

地址澳大利亚

24 岁

姓名 Rica

地址亚洲

25 岁

输出 姓名 Rico,地址澳大利亚,24 岁

姓名 Rica,地址亚洲,25 岁​​

我们可以在 Unix 中这样做吗?

您可以使用 awk 将多行转换为单行。

#!/usr/bin/awk
# table.awk

{
    if (NR == 1) {
        printf("%s",[=10=]);
    } else {
        printf(",%s",[=10=]);
    }
}

$猫input.csv

Name Rico
Address Australia
Age 24
Name Rica
Address Asia
Age 25

$ awk -f table.awk input.csv

Name Rico,Address Australia,Age 24,Name Rica,Address Asia,Age 25

Whosebug 中有更有效的答案,如下所示:

How to merge rows from the same column using unix tools

这是另一种选择...

paste -sd, inputfile

使用 sed:

sed ':a;N;$!ba;s/\n/, /g' filename

我找到了解决方案:

awk 'BEGIN { RS="" ; FS="\n"}; { print , }' 文件

这会将输入记录分隔符设置为空白行,或为此问题设置连续的空白行,因为下一条记录将是下一个非空白行。这还将字段分隔符设置为下一行。