2012-09-24 61 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