使用Awk创建csv行

时间:2012-07-05 17:49:16

标签: sed awk

我是awk的新手,无法找到最好的方法。 我有几千个xml文件,我已经使用sed和awk将重复项和分割的字段删除到单个文件中的单个列中。

现在我想将列表组装成一行包含多个字段的csv文件。在固定数量的字段之后,我想开始一个新的行。

实施例

1234
2345

345678
4.23456E3
54321
654321
789

87654.100
9876

10.0
1234
2345

345678
4.23456E3
54321
654321
789

87654.100
9876

11.0

输出

1234, 2345, , 345678, 4.23456E3, 54321, 654321, 789, , 87654.100, 9876, , 10.0
1234, 2345, , 345678, 4.23456E3, 54321, 654321, 789, , 87654.100, 9876, , 11.0

由于

4 个答案:

答案 0 :(得分:2)

是否允许使用xargs

cat input | xargs -L13 -d'\n' | sed -e 's/ /, /g'

我在这里得到这个输出:

1234, 2345, , 345678, 4.23456E3, 54321, 654321, 789, , 87654.100, 9876, , 10.0
1234, 2345, , 345678, 4.23456E3, 54321, 654321, 789, , 87654.100, 9876, , 11.0

但是,如果你开始使用XML,你应该考虑使用XSLT。

答案 1 :(得分:2)

如果每一行都有相同数量的字段,比如5,我会做类似的事情

awk ' { printf("%s",$1); if (NR % 5 == 0) {printf("\n")} else {printf(",")}}' youtfile.txt

NR是awk读取的行数,%是余数运算符。因此,如果读取的行数是5的倍数(在这种情况下),它将打印换行符,否则将打印逗号。

假设您的示例中每行一个字段,并且输入中的空白行将对应于CSV中的空白字段。

答案 2 :(得分:2)

使用sed的一种方式:

script.sed的内容:

## Label 'a'
:a

## If last line, print what is left in the buffer, substituting
## newlines with commas.
$ {
    s/^\n//
    s/\n/, /g
    p   
    q   
}

## If content of buffer has 12 newlines, we have reached to the limit
## of the line, so remove newlines with commas, print and delete buffer
## overwritting it with 'b'
/\([^\n]*\n\)\{12\}/ {
    s/^\n//
    s/\n/, /g
    p   
    b   
}

## Here buffer has not reached to the limit of fields for each line, so
## append one more (N) and continue loop in label 'a'
N
ba

像以下一样运行:

sed -nf script.sed infile

使用以下输出:

1234, 2345, , 345678, 4.23456E3, 54321, 654321, 789, , 87654.100, 9876, , 10.0
1234, 2345, , 345678, 4.23456E3, 54321, 654321, 789, , 87654.100, 9876, , 11.0

答案 3 :(得分:0)

这可能对您有用:

paste -sd',,,,,,,,,,,,\n' file | sed 's/,/, /g'
1234, 2345, , 345678, 4.23456E3, 54321, 654321, 789, , 87654.100, 9876, , 10.0
1234, 2345, , 345678, 4.23456E3, 54321, 654321, 789, , 87654.100, 9876, , 11.0

或者这个(GNU sed):

sed ':a;$bb;N;s/\n/&/12;Ta;:b;s/\n/, /g' file
1234, 2345, , 345678, 4.23456E3, 54321, 654321, 789, , 87654.100, 9876, , 10.0
1234, 2345, , 345678, 4.23456E3, 54321, 654321, 789, , 87654.100, 9876, , 11.0
相关问题