将第 n 次出现的 'foo' 替换为所提供文件的相应第 n 行的数字
Replace each nth occurrence of 'foo' by numerically respective nth line of a supplied file
我在发布此问题之前寻找解决方案,但我只是找到了中间答案,例如 this。我感觉很有可能有和我一模一样或者相似的问题,但是我没有发现这样的事情。
我想将 1.txt 文件 中第 n 次出现的 foo
替换为 [ 的第 n 行数字对应行=42=] 文件 包含以下内容(这是 MWE)。
0.txt:
The sun has its own light
foo
The moon reflects the sunlight
foo
The planet Earth receives both sunlight and moonlight
foo
1.txt:
cat1.frog1_rain1 (('f1','b1'), ('g1','h1'))
cat2.frog2_rain2 (('f2','b2'), ('g2','h2'))
cat3.frog3_rain3 (('f3','b3'), ('g3','h3'))
应用替换,例如'command_method' 0.txt 1.txt > 2.txt
(伪代码),我希望输出文件如下,是第三个 2.txt 文件:
上的打印输出
2.txt:
The sun has its own light
cat1.frog1_rain1 (('f1','b1'), ('g1','h1'))
The moon reflects the sunlight
cat2.frog2_rain2 (('f2','b2'), ('g2','h2'))
The planet Earth receives both sunlight and moonlight
cat3.frog3_rain3 (('f3','b3'), ('g3','h3'))
请您尝试 awk
解决方案:
awk 'NR==FNR {a[NR]=[=10=]; next} /foo/{gsub("foo", a[++i])} 1' 1.txt 0.txt > 2.txt
我在发布此问题之前寻找解决方案,但我只是找到了中间答案,例如 this。我感觉很有可能有和我一模一样或者相似的问题,但是我没有发现这样的事情。
我想将 1.txt 文件 中第 n 次出现的 foo
替换为 [ 的第 n 行数字对应行=42=] 文件 包含以下内容(这是 MWE)。
0.txt:
The sun has its own light
foo
The moon reflects the sunlight
foo
The planet Earth receives both sunlight and moonlight
foo
1.txt:
cat1.frog1_rain1 (('f1','b1'), ('g1','h1'))
cat2.frog2_rain2 (('f2','b2'), ('g2','h2'))
cat3.frog3_rain3 (('f3','b3'), ('g3','h3'))
应用替换,例如'command_method' 0.txt 1.txt > 2.txt
(伪代码),我希望输出文件如下,是第三个 2.txt 文件:
2.txt:
The sun has its own light
cat1.frog1_rain1 (('f1','b1'), ('g1','h1'))
The moon reflects the sunlight
cat2.frog2_rain2 (('f2','b2'), ('g2','h2'))
The planet Earth receives both sunlight and moonlight
cat3.frog3_rain3 (('f3','b3'), ('g3','h3'))
请您尝试 awk
解决方案:
awk 'NR==FNR {a[NR]=[=10=]; next} /foo/{gsub("foo", a[++i])} 1' 1.txt 0.txt > 2.txt