2012-07-11 51 views
1

我有一個文件,其頭部記錄後跟詳細信息行。我希望使用awk將標題中的單詞標記爲文件中的後續行。每個標題記錄都有一個特定的單詞「標題」。使用awk將頭文件中的第一個單詞添加到文件的所有後續行中

我的樣本文件

h1_val header 
this is line 1 under header set1 
this is line 2 under header set1 
this is line 3 under header set1 
this is line 4 under header set1 
h2_val header 
this is line 1 under header set2 
this is line 2 under header set2 
this is line 3 under header set2 
this is line 4 under header set2 

我的輸出應該像

h1_val this is line 1 under header set1 
h1_val this is line 2 under header set1 
h1_val this is line 3 under header set1 
h1_val this is line 4 under header set1 
h2_val this is line 1 under header set2 
h2_val this is line 2 under header set2 
h2_val this is line 3 under header set2 
h2_val this is line 4 under header set2 

請幫

謝謝!

感謝ghoti看來,如果線是純如果我輸入看起來像逗號分隔並用雙引號工作正常.. ......應該awk的是什麼樣的變化

"h1_val","header word" 
"this is line 1","under header","set1" 
"this is line 2","under header","set1" 
"this is line 2","under header","set1" 
"this is line 2","under header","set1" 
"h2_val","header word" 
"this is line 1","under header","set2" 
"this is line 2","under header","set2" 
"this is line 2","under header","set2" 
"this is line 2","under header","set2" 

謝謝!

+2

爲什麼你沒有在第一位指定這些條件? – 2012-07-11 03:57:46

回答

2

這似乎是這樣做的。

$ awk '$2=="header"{h=$1;next} {printf("%s ",h)} 1' input.txt 
h1_val this is line 1 under header set1 
h1_val this is line 2 under header set1 
h1_val this is line 3 under header set1 
h1_val this is line 4 under header set1 
h2_val this is line 1 under header set2 
h2_val this is line 2 under header set2 
h2_val this is line 3 under header set2 
h2_val this is line 4 under header set2 

或者,如果你願意的話,這是功能上等同:

$ awk '$2=="header"{h=$1;next} {print h " " $0}' input.txt 

注意,這些意味着你的標題文字沒有空格。如果確實如此,那麼你可能需要做一些比$2=="header"更加奇特的事情來找到你的標題。如果是這種情況,請詳細說明update your question

+0

感謝ghoti它似乎是工作的罰款,如果線路是純.. 如果我輸入看起來像逗號分隔並用雙引號......應該awk的是什麼樣的變化 「h1_val」,「頭文字」 「這是行1「,」標題下「,」set1「 」這是行2「,」標題下「,」set1「 」這是行2「,」標題下「,」set1「 」這是第2行「,」標題下「,」set1「 」h2_val「,」標題詞「 」這是行1「,」標題下「,」set2「 」這是行2「,」標題下「 「set2」 「this is line 2」,「under header」,「set2」 「this is line 2」,「under header」,「set2」 謝謝! – user1516461 2012-07-11 03:18:13

+0

正如我在我的答案暗示,你應該點擊您的問題下的[**編輯**](http://stackoverflow.com/posts/11424847/edit)鏈接,並更新您的問題與更多細節,如果有細節這將改善你得到的答案。 StackOverflow評論做可怕的格式。請更新您的問題,我會更新我的答案。 – ghoti 2012-07-11 03:21:16

+0

哦,我會提到,逗號+引號分隔的文本不太可能被awk完美處理。如果逗號是您的字段分隔符,那麼awk不會知道內部逗號與外部引號之間的區別。當然,如果你在引號內沒有逗號,你應該沒問題。 – ghoti 2012-07-11 03:23:09

1
> awk '{if($2=="header")p=$1;else print p,$0}' temp2 
h1_val this is line 1 under header set1 
h1_val this is line 2 under header set1 
h1_val this is line 3 under header set1 
h1_val this is line 4 under header set1 
h2_val this is line 1 under header set2 
h2_val this is line 2 under header set2 
h2_val this is line 3 under header set2 
h2_val this is line 4 under header set2 
相關問題