将每个第 n 次出现的 'foo' 替换为所提供文件的第 n 行数字 [英] Replace each nth occurrence of 'foo' by numerically respective nth line of a supplied file

查看:34
本文介绍了将每个第 n 次出现的 'foo' 替换为所提供文件的第 n 行数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在发布此问题之前寻找了解决方案,但我只找到了中间答案,例如 this .我觉得很可能有和我完全一样或类似的问题,但我没有发现这样的问题.

I looked for a solution before posting this issue but I just found intermediate answers such as this . I feel that it is very likely to have any questions exactly or similar to mine, but I have not found such a matter.

我想用 0.txt 文件的第 n 个数字对应行替换 1.txt 文件 中每个出现的 foo> 包含以下内容(这是 MWE).

I would like to replace each nth occurrence of foo on the 1.txt file by nth numerically corresponding line of a 0.txt file containing the following content below (this is 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 文件上的打印输出:

Applying the replacement, e.g. 'command_method' 0.txt 1.txt > 2.txt (pseudocode), I would have the desired output file is as below, being the printed output on a third 2.txt file:

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 解决方案:

Would you please try the awk solution:

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

这篇关于将每个第 n 次出现的 'foo' 替换为所提供文件的第 n 行数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆