如何从文件的一个部分获取文本并插入到同一文件的另一部分?

问题描述 投票:0回答:1

所以,想象我有一大堆像这样的文件:

a line of text
some marker: useful_information
a line of text
a line of text
a line of text
I need to insert here
a line of text
a line of text

我需要将

useful_information
从文件顶部附近出现的行复制到文件中稍后的
insert
here
之间的位置:

a line of text
some marker: useful_information
a line of text
a line of text
a line of text
I need to insert useful_information here
a line of text
a line of text

useful_information
因文件而异,但
some marker: 
始终位于其前面,并且始终以行尾结束。两行之间的行数是可变的,但定义目标的行在所有文件中都是相同的。

鉴于我有大量文件需要执行此操作,我想使用 sed 或 awk 等工具批量执行此操作。那么如何从一行复制一些文本并将其放入同一个文件中另一行的特定位置中?

awk sed
1个回答
0
投票

使用 awk:

awk -v marker="some marker:" '
$0~marker {s=$0; sub(marker,"", s)} 
$0~"I need to insert here" {sub(/I need to insert /,"I need to insert" s "here")}
1' file
© www.soinside.com 2019 - 2024. All rights reserved.