自动将指定文件插入另一个文件(使用 sed、AWK 或 Perl) [英] Automatically inserting specified file into another (using sed, AWK, or Perl)
问题描述
假设我有一个文件,Foo.in
:
Contents of Foo
和 Bar.in
INSERT Foo.in
Contents of Bar
我想编写一个 sed
脚本,用 xyz
文件的实际内容替换 INSERT xyz
.在这个特定的例子中,我想生成 Bar.out
文件,其中包含:
I would like to write a sed
script that replaces INSERT xyz
with actual contents of the xyz
file. In this particular example I'd like to produce Bar.out
file containing:
Contents of Foo
Contents of Bar
我考虑过使用 sed
的 r
命令作为演示 在这个堆栈溢出问题中,但问题是要插入的文件在文件本身中指定.我想过扫描文件中的 INSERT
命令,然后为每个找到的 INSERT
分别运行 sed
,但这是 O(n^2) 复杂性.我更喜欢使用 sed 或 AWK 来执行此操作,但如果所有其他方法都失败,则可以使用 Perl 脚本.
I thought about using sed
's r
command as demonstrated in this Stack Overflow question, but the problem is that the name of the file to be inserted is specified in the file itself. I thought about scanning the file for INSERT
commands and then running sed
separately for every INSERT
found, but that is a horrible solution with O(n^2) complexity. I'd prefer to do this using sed or AWK, but if all else fails a Perl script would be acceptable.
推荐答案
$ cat Foo.in
Contents of Foo
$ cat Bar.in
INSERT Foo.in
Contents of Bar.in
$ awk '/INSERT/{while((getline line < $2) > 0 ){print line}close($2);next}1' Bar.in
Contents of Foo
Contents of Bar.in
这篇关于自动将指定文件插入另一个文件(使用 sed、AWK 或 Perl)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!