自动将指定文件插入另一个文件(使用 sed、AWK 或 Perl) [英] Automatically inserting specified file into another (using sed, AWK, or Perl)

查看:51
本文介绍了自动将指定文件插入另一个文件(使用 sed、AWK 或 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

我考虑过使用 sedr 命令作为演示 在这个堆栈溢出问题中,但问题是要插入的文件在文件本身中指定.我想过扫描文件中的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆