用grep或类似的东西添加具有相同结构的额外行

问题描述

我正在尝试在发现一个单词的每个文件中写一个,让我说我拥有

>>grep one ~/home/docs/*
/numbers.txt one is a number
/integers.txt one is an integer

我需要在其下方添加一条额外的行,该行表示几乎相同,但用第二个来代替

“经过一些编码,我可以在其中添加第二行(...)”

我应该会写

>>grep two ~/home/docs/*
/numbers.txt two is a number
/integers.txt two is an integer

解决方法

您的要求可以分为3个步骤:

  1. 找到所有包含关键字ex的文件:one

    fgrep -l一个*

  2. 使用for循环遍历第一步中列出的所有文件

    用于$(grep -l one *)中的文件;做;完成

  3. 在每次迭代中执行一个操作,将自定义行添加到所述文件中

    用于$(grep -l one *)中的文件;做echo“在此文件中找到一个,以便添加此客户行” >> $ file;完成

因此,如第3点所述,最终命令将是

for file in $( grep -l one *); do sed -i 's/one/two/g' $file ;echo "found one in this file so replacing it with two " >> $file ; done