【问题标题】:Use sed/cat to add text from 1 file after matched pattern in multiple files使用 sed/cat 在多个文件中匹配模式后从 1 个文件中添加文本
【发布时间】:2019-04-13 06:39:50
【问题描述】:

我需要将 1 个文件中的文本添加到 2 个标签之间的多个文件中。所有文件都具有相同的扩展名 .sh 但名称不同,并且都在子目录中。

我尝试修改它,但它仅适用于搜索和替换:

file=$(cat file1.txt)
replace="s/end=date +%s/$file/g";
find . -type f -name '*.sh' -print0 | xargs -0 sed -i "$replace" 

file1.txt

some text here
some text here
some text here
some text here
some text here

file1.txt 的最终输出和内容作为新行添加到所有 .sh 文件的 end=date +%s 下

end=date +%s
some text here
some text here
some text here
some text here
some text here

【问题讨论】:

  • 我们的目标是在您的问题中添加一些您自己的代码,以至少显示您为解决这个问题所做的研究工作。
  • 既然你已经成功完成了一个,你可以粘贴代码sn-p吗?
  • 对不起,我用我试过但没用的方法更新了问题
  • 您真的想add text from 1 file to multiple files between 2 tags 还是只是想在 1 个标签之后附加文件的内容?如果存在/dir/$tag.tar.gz 但下一行不是end=`date +%s`,脚本应该怎么做?

标签: sed cat


【解决方案1】:

在 bash shell 上尝试 gnu sed,不带 -i 选项进行测试;

sed -E '/end=date\s+\+%s/r file1.txt' *.sh

测试后将 -i 选项添加到真实编辑,例如sed -Ei....
要递归搜索 subs 中的文件,请使用 find 执行此操作并将找到的文件发送到 sed
find ~+ -iname '*.sh' -exec sed -E '/end=date\s++%s/r file1.txt' '{}' +

【讨论】:

  • sed: -e expression #1, char 52: unterminated `s' command 知道吗?我改变了我的问题,最好在新行之后插入:end=date +%s
  • 它似乎不适用于子目录,但仅适用于同一目录中的文件,有什么建议吗?
猜你喜欢
  • 1970-01-01
  • 2017-12-15
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
  • 2020-07-07
  • 2016-04-21
  • 2021-04-02
  • 2011-06-03
相关资源
最近更新 更多