将第 n 次出现的 'foo' 替换为给定文件中第 n 个连续的常规行范围

Replace every nth occurrence of 'foo' with the nth consecutive regular range of lines from a given file

我想将 1.txt 文件中 foo 的每个 nth 事件替换为第 n 个连续的 每第 n 行的常规行范围在这种情况下说每 2 行 )来自 0.txt 文件,其中包含以下内容(这是 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:

source-text1
[(('f1','b1'), ('g1','h1'))]
source-text-2
[(('f2','b2'), ('g2','h2'))]
source-text-3
[(('f3','b3'), ('g3','h3'))]

正在应用替换,例如'command_method' 0.txt 1.txt > 2.txt ,伪代码,我想要的输出文件如下,是第三个 2.txt 文件的打印输出:

预期输出为 2.txt:

The sun has its own light
source-text1
[(('f1','b1'), ('g1','h1'))]
The moon reflects the sunlight
source-text-2
[(('f2','b2'), ('g2','h2'))]
The planet Earth receives both sunlight and moonlight
source-text-3
[(('f3','b3'), ('g3','h3'))]

我试过了:

awk 'NR==FNR {a[NR]=[=14=]; next} /foo/{gsub("foo", a[int(k++/2)%3 + 2])} 1' 1.txt 0.txt > 2.txt

但这给了我 2.txt:

The sun has its own light
[(('f1','b1'), ('g1','h1'))]
The moon reflects the sunlight
[(('f1','b1'), ('g1','h1'))]
The planet Earth receives both sunlight and moonlight
source-text-2

我没有想法了。我正在寻找一种可以处理任何大小范围的线的解决方案

假设:

  • foo 只出现在一行中
  • 如果 foo 出现的次数多于我们的替换字符串,请不要替换 foo

设置:

$ cat 0.txt
The sun has its own light
foo
The moon reflects the sunlight
foo
The planet Earth receives both sunlight and moonlight
foo
The following line should NOT be replaced
foo

$ cat 1.txt
source-text1
[(('f1','b1'), ('g1','h1'))]
source-text-2
[(('f2','b2'), ('g2','h2'))]
source-text-3
[(('f3','b3'), ('g3','h3'))]

一个awk想法:

awk -v setsize=2 -v ptn="foo" '                        # setsize == number of lines from first file that define a replacement set
                                                       # ptn == string to be replaced

FNR==NR { replace[++rcount]= [=11=]                        # start replacement string
          for (i=1;i<setsize;i++) {                    # append to replacement string until we have read "setsize" lines into the replacement string
              getline
              replace[rcount]=replace[rcount] RS [=11=]
          }
          next
        }
[=11=]~ptn  { if (++pcount in replace)                     # if we have a replacement string then ...
              [=11=]=replace[pcount]                       # replace the current line
        }
1                                                      # print the current line

' 1.txt 0.txt

这会生成:

The sun has its own light
source-text1
[(('f1','b1'), ('g1','h1'))]
The moon reflects the sunlight
source-text-2
[(('f2','b2'), ('g2','h2'))]
The planet Earth receives both sunlight and moonlight
source-text-3
[(('f3','b3'), ('g3','h3'))]
The following line should NOT be replaced
foo