2012-09-24 31 views
3

我有一个看起来像这样的文件部分:

awk中:修改CSV含头

Downtown 
3/1/2013, 6A, 1 convertible to 2 bedroom apartment, tile bath, air conditioning, $3800 
4/1/2013, 4C, One bedroom living room eat-in-kitchen, $3850 
East Village 
5/17/2013, 9M, STUDIO K'ETTE air conditioner TILE BATH, $2300 
6/1/2013, 6H, Studio with tile bath and kitchenette with stone counters tops, $2600 
SoHo 
6/1/2013, 10B ,STUDIO KETTE air conditioner TILE BATH, $2400 

(等)

我希望它转换为是这样的:

Downtown, 3/1/2013, 6A, 1 convertible to 2 bedroom apartment, tile bath, air conditioning, $3800 
Downtown, 4/1/2013, 4C, One bedroom living room eat-in-kitchen, $3850 
East Village, 5/17/2013, 9M, STUDIO K'ETTE air conditioner TILE BATH, $2300 
East Village, 6/1/2013, 6H, Studio with tile bath and kitchenette with stone counters tops, $2600 
SoHo, 6/1/2013, 10B ,STUDIO KETTE air conditioner TILE BATH, $2400 

我不知道如何把这些部分的标题,并将它们移动到列,以便我有一个完整的描述表...我相信用awk最容易做到,但是有人可以提供一段代码,或者说明如何用awk(或者其他最合适的命令)来完成这个工作?

谢谢!

回答

5

给出一个名为“test.txt”的文件,其中包含您在下面描述的数据。你可以用下面的AWK行得到它:

awk -F"," 'NF == 1 {header = $0;} NF > 1 {print header", "$0;}' test.txt 

如果num字段为1的是一个头,所以我把它保存在“头”变量。 如果Num Fields大于1,那么它是一个“数据行”,所以我输出“header”的最后一个值和整个“data line”。

它的工作对我来说:

Downtown, 3/1/2013, 6A, 1 convertible to 2 bedroom apartment, tile bath, air conditioning, $3800 
Downtown, 4/1/2013, 4C, One bedroom living room eat-in-kitchen, $3850 
East Village, 5/17/2013, 9M, STUDIO K'ETTE air conditioner TILE BATH, $2300 
East Village, 6/1/2013, 6H, Studio with tile bath and kitchenette with stone counters tops, $2600 
SoHo, 6/1/2013, 10B ,STUDIO KETTE air conditioner TILE BATH, $2400 
+0

烨,这就是答案!我认为awk是去这里的路。不知道你可以在awk语句中设置一个变量 - 非常酷! – user1642475

1

这可能为你工作(GNU SED):

sed -i '/,/!{h;d};G;s/\(.*\)\n\(.*\)/\2, \1/' file