gpt4 book ai didi

awk - 使用 awk 将标题中的第一个单词添加到文件的所有后续行

转载 作者:行者123 更新时间:2023-12-02 22:36:06 26 4
gpt4 key购买 nike

我有一个文件,其中包含标题记录,后跟详细信息行。我想使用 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"

谢谢!!

最佳答案

这似乎可以做到。

$ 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" 更高级的事情来找到您的 header 。如果是这种情况,那么请update your question有更多的细节。

关于awk - 使用 awk 将标题中的第一个单词添加到文件的所有后续行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11424847/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com