与sed匹配的多个文件匹配后追加新行

时间:2020-06-17 20:06:53

标签: bash sed

我正在写脚本

脚本的一个目标是在匹配后,在多个.yml文件中添加新的 codeline foo 递归地。

# Append new line after match in multiple files with sed
## sed -i -se "s/\foo/bar/g" *.yml
grep -rl foo * .| xargs sed -i -e "s/\foo/a bar/g" *.yml
在与 foo 的每次比赛后

期望,由于/a bar 将被添加到新行中.yml个文件。

意外出现Sed支出: sed: can't read *.yml: No such file or directory

详细信息:

  1. 操作系统:Debian GNU / Linux 10
  2. sed --version:sed(GNU sed)4.7

1 个答案:

答案 0 :(得分:2)

您要为文件名参数提供xargs。您也不应使用*.yml作为参数。 Shell会将其扩展到当前目录中的.yml文件,如果没有,则会出现错误。

如果您希望grep -r仅检查.yml个文件,请使用--include选项。

grep -rl --include='*.yml' foo . | xargs sed -i -e "s/foo/a bar/g"

请注意,s命令不用于在一行之后添加新行。用于替换同一行。 s/foo/ a bar/gfoo替换行中的所有a bar。如果要追加,请摆脱s命令。另外,您不要将/g放在a命令的末尾。

grep -rl --include='*.yml' foo . | xargs sed -i -e "/foo/a bar"

请参见How to insert text after a certain string in a file?