0

我需要更改列的顺序(即顺序)

# cat customer.csv
customerno, firstname, lastname, sales
23242, john, doe, 2345.00
23253, jane, doe, 1234.00
23221, greg, johnson, 2345.00
23210, howard, gardner, 2345.00

这有效,但第一列后没有逗号。

# awk  '{print $4, $3, $2, $1}' customer.csv
sales lastname, firstname, customerno,
2345.00 doe, john, 23242,
1234.00 doe, jane, 23253,
2345.00 johnson, greg, 23221,
2345.00 gardner, howard, 23210,

如何删除最后的逗号?有没有一种优雅的方式来做到这一点?

# awk  '{print $4 ",", $3, $2, $1}' customer.csv
sales, lastname, firstname, customerno,
2345.00, doe, john, 23242,
1234.00, doe, jane, 23253,
2345.00, johnson, greg, 23221,
2345.00, gardner, howard, 23210,
4

4 回答 4

2

使用逗号 + 空格作为分隔符并在打印列时打印必要的逗号:

awk -F", " '{print $4",", $3",", $2",", $1}' filename
于 2012-10-15T08:46:49.247 回答
1

如果您想在 python 中执行此操作(您的标记会建议),请尝试以下操作:

f = open('customer.csv')
for line in f:
    line = line.strip().split(', ')
    line.reverse()
    print ', '.join(line)

或者,如果要将结果输出到文件:

f = open('customer.csv')
out = ''
for line in f:
    line = line.strip().split(', ')
    line.reverse()
    out += ', '.join(line) + '\n'
f.close()

f = open('customer2.csv', 'w')
f.write(out)
f.close()
于 2012-10-15T09:10:46.203 回答
1
awk '{sub(",",""); print $4", " $3, $2, $1}' file
于 2012-10-15T11:27:18.940 回答
1

你很接近,你只是忘了设置你的字段分隔符:

$ awk  'BEGIN{FS=OFS=", "} {print $4, $3, $2, $1}' customer.csv
sales, lastname, firstname, customerno
2345.00, doe, john, 23242
1234.00, doe, jane, 23253
2345.00, johnson, greg, 23221
2345.00, gardner, howard, 23210
于 2012-10-15T14:08:39.167 回答