使用awk将头中的第一个字添加到文件的所有后续行

使用awk将头中的第一个字添加到文件的所有后续行,awk,Awk,我有一个文件,头记录后面跟着详细信息行。我希望使用awk将单词从标题标记到文件中的后续行。。每个标题记录中都有一个特定的单词“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 l

我有一个文件,头记录后面跟着详细信息行。我希望使用awk将单词从标题标记到文件中的后续行。。每个标题记录中都有一个特定的单词“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" 
谢谢

这似乎可以做到

$ 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”
更奇特的事情来查找您的头。如果是这种情况,请提供更多详细信息。

谢谢ghoti,如果线条清晰,效果似乎很好。。如果我的输入看起来像逗号分隔的并且带有双引号。。。awk应为“h1_val”、“标题词”“这是第1行”、“标题下”、“set1”“这是第2行”、“标题下”、“set1”“这是第2行”、“标题下”、“set1”“这是第2行”、“标题下”、“set1”“h2_val”、“标题词”“这是第1行”、“标题下”、“set2”“这是第2行”、“标题下”、“set2”“这是第2行”,“在标题下”、“设置2”这是第2行、“在标题下”、“设置2”“谢谢!!正如我在回答中所暗示的,如果有细节可以改善你得到的答案,你应该点击你问题下的链接,并用更多细节更新你的问题。StackOverflow注释的格式很糟糕。请更新您的问题,我将更新我的答案。哦,我要提到的是,逗号+引号分隔的文本不太可能被awk完美地处理。如果逗号是字段分隔符,awk不知道引号内逗号和引号外逗号的区别。当然,如果你的引号里没有逗号,你应该没事。我试过这样。。。但它不会在第一个单词后添加逗号…任何输入都是非常感谢的…谢谢!!awk-F,'$2==“\”标题词\'{h=$1;next}{printf(“%s”,h)}1”输入。TXT最终解决了这个问题……awk-F,'$2==“\”标题词\'{h=$1;next}{printf(“%s,”,h)}1”输入。TXT为什么不首先指定这些条件?
> 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