gpt4 book ai didi

linux - 将一个文件中的特定行替换为另一文件中包含的数据

转载 作者:太空宇宙 更新时间:2023-11-04 05:46:10 25 4
gpt4 key购买 nike

我想用另一个文件(文件 2)中包含的数据替换一个文件(文件 1)中的特定行。例如:文件1(输入代码):

 other lines...
11 !!! Regular Expression
10 0.685682*100
11 0.004910*100
12 0.007012*100
13 0.146041*100
14 0.067827*100
15 0.019460*100
16 0.019277*100
17 0.001841*100
18 0.047950*100
other lines...

文件 2(添加新数据):

 1 0.36600*100
2 0.44466*100
3 0.0.046*100
4 0.15544*100
5 0.16600*100
6 0.14477*100
7 0.01927*100
8 0.00188*100
9 0.05566*100

如何用文件 2(数据)中包含的数据替换第 1 行到第 n 行的输入数据(文件 1)。我尝试使用 sed 如下:

sed '/!!! Regular Expresion/r File2' File1

我得到以下信息:

 1 !!! Regular Expression
2 0.36600*100
3 0.44466*100
4 0.0.046*100
5 0.15544*100
6 0.16600*100
7 0.14477*100
8 0.01927*100
9 0.00188*100
10 0.05566*100
11 0.685682*100
12 0.004910*100
13 0.007012*100
14 0.146041*100
15 0.067827*100
16 0.019460*100
17 0.019277*100
19 0.001841*100
20 0.047950*100

我的问题是该命令可以插入文件 2 中包含的行但不能替换它们。如何用新数据仅替换这些行(从 10 到 18)?

提前致谢。

最佳答案

replace specific lines in one file from 10 to 18 with the data contained in File 2

让我们使用动态规划,将“替换”拆分为“删除”和“插入”。

[Delete] specific lines in one file from 10 to 18

这很简单:

sed '10,18d'

将删除第 10 到 18 行。

[Insert] the data contained in File 2 [to line 10]

这也很简单:

sed '9r file2'

它将 file2 的内容追加到第 9 行之后,因此 file2 的第一行是新的第 10 行。

一起:

sed '10,18d; 9r file2'

示例:

# seq 8 | sed '3,6d; 2r '<(seq -f 2%.0f 5)
1
2
21
22
23
24
25
7
8

关于linux - 将一个文件中的特定行替换为另一文件中包含的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58227689/

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