我有一个带有标题记录的文件,后跟详细信息行。我希望使用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"
谢谢!
答案 0 :(得分: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。
答案 1 :(得分: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