首页 > 解决方案 > 将每第 n 次出现的 'foo' 替换为所提供文件的数字相应第 n 行

问题描述

我在发布此问题之前寻找了解决方案,但我只是找到了诸如此类的中间答案。我觉得很有可能有什么问题和我的一模一样或者类似,但是我没有发现这样的问题。

我想用包含以下内容的0.txt 文件的第 n 个数字对应行替换1.txt 文件foo中的第 n 个出现(这是 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'))

标签: stringbashreplacetext-processing

解决方案


请您尝试awk解决方案:

awk 'NR==FNR {a[NR]=$0; next} /foo/{gsub("foo", a[++i])} 1' 1.txt 0.txt > 2.txt

推荐阅读