【问题标题】:Replace each nth occurrence of 'foo' by numerically respective nth line of a supplied file用提供的文件的数字相应的第 n 行替换每第 n 次出现的 'foo'
【发布时间】:2021-06-18 16:14:04
【问题描述】:

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

我想用包含以下内容的 0.txt 文件 中的第 n 个数字对应行替换 1.txt 文件 中出现的第 n 个 foo下面(这是 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 'NR==FNR {a[NR]=$0; next} {gsub("foo", a[++i])} 1' 1.txt 0.txt > 2.txt
  • 嗯...我无法重现您的问题。
  • 很抱歉给您带来不便。那怎么样:awk 'NR==FNR {a[NR]=$0; next} /foo/{gsub("foo", a[++i])} 1' 1.txt 0.txt > 2.txt
  • 好的。我会把它留给你。
  • 好的,我已经发布了我的答案。

标签: string bash replace text-processing


【解决方案1】:

请您尝试awk 解决方案:

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

【讨论】:

    猜你喜欢
    • 2021-12-19
    • 2021-10-12
    • 2018-09-08
    • 2018-08-11
    • 2018-03-24
    • 1970-01-01
    • 2014-03-31
    • 2015-06-23
    • 2021-12-20
    相关资源
    最近更新 更多