使用sed在给定行的多个文件中插入文件内容

时间:2014-04-10 10:44:11

标签: bash sed

我想在当前文件夹和子文件夹中找到与模式(cs*.dat3)匹配的所有文件,并将文件块从文件或bash变量插入到给定行中。 可以也可以在匹配文件中的模式而不是给定的行之后,但我有

PRESSURE_RELIEF_PANELS
EXIT PRESSURE_RELIEF_PANELS

所以这些东西会放两次。幸运的是,第一个PRESSURE_RELIEF_PANELS总是在第32行,因此可以使用。我目前的看法是:

find . -name cs*.dat3 -exec sed '33iblah' {} \;

输出

PRESSURE_RELIEF_PANELS
blah
EXIT PRESSURE_RELIEF_PANELS

现在,我想插入一个文本块,而不是“blah”。此文本存储在一个文件中,因此它可以临时存储在bash变量中,也可以以某种方式作为路径或文件读入sed。我无法找到一个好的解决方案,因为我无法将sed的insert语句(i)与filename语句(r)结合起来

任何?

2 个答案:

答案 0 :(得分:3)

您可以将读取文件命令与地址一起使用。话说:

sed '33rfile' input

会在file

中的第33行之后插入名为input的文件

您可能已经意识到r是GNU扩展。

从手册中引用:

  

`r FILENAME'

 As a GNU extension, this command accepts two addresses.

 Queue the contents of FILENAME to be read and inserted into the
 output stream at the end of the current cycle, or when the next
 input line is read.  Note that if FILENAME cannot be read, it is
 treated as if it were an empty file, without any error indication.

 As a GNU `sed' extension, the special value `/dev/stdin' is
 supported for the file name, which reads the contents of the
 standard input.

答案 1 :(得分:1)

你可以这样做:

find . -name cs*.dat3 -exec sed -i.bak '/^PRESSURE_RELIEF_PANELS$/r file.dat' '{}' \;

file.dat将要插入数据。