2

我有一个带有标题记录的文件,后跟详细信息行。我希望使用 awk 将 header 中的单词标记到文件中的后续行。每个 Header 记录中都有一个特定的单词“header”。

我的示例文件是

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" 

谢谢!!

4

2 回答 2

3

这似乎做到了。

$ 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 OFS $0}' input.txt

请注意,这意味着您的标题文本没有空格。如果是这样,那么您可能需要做一些比$2=="header"查找标题更有趣的事情。如果是这种情况,请更详细地更新您的问题。

于 2012-07-11T02:55:53.897 回答
2
> 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
于 2012-07-11T05:36:54.037 回答