【问题标题】:Adding extra lines with same structure with grep (or something like that)使用 grep (或类似的东西)添加具有相同结构的额外行
【发布时间】:2020-09-13 07:39:37
【问题描述】:

我正在尝试在我找到的每个文件中写入一个单词,假设我有

>>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

【问题讨论】:

  • 请将该示例输入的所需输出(无描述)添加到您的问题(无评论)。

标签: grep code-duplication


【解决方案1】:

您的要求可以分为 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

【讨论】:

  • 谢谢,它确实有效。但是我仍然需要复制上一行并逐个更改元素
  • @ErickMunive 我已经编辑了我的答案,将 'one' 替换为 'two' 并保留了 echo 语句,以便在文件中附加您的自定义字符串。
猜你喜欢
  • 1970-01-01
  • 2011-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-05
  • 2021-11-04
  • 1970-01-01
相关资源
最近更新 更多