0

我正在尝试根据特定标准替换文本文件中的文本。

例如,如果我有三个文本文件,其中 outer.txt 包含:

   Blah Blah Blah
   INCLUDE inner1.txt
   Etcetera Etcetera
   INCLUDE inner2.txt
   end of file

和 inner1.txt 包含:

  contents of inner1

和 inner2.txt 包含:

  contents of inner2

在替换结束时,outer.txt 文件如下所示:

    Blah Blah Blah
    contents of inner1
    Etcetera Etcetera
    contents of inner2
    end of file

总体模式是,对于单词“INCLUDE”的每个实例,将整行替换为文件名紧跟“INCLUDE”实例之后的文件的内容,在一种情况下是 inner1.txt,在第二种情况下案例将是 inner2.txt。

更简单地说,gawk 是否有可能根据外部文本文件中要替换的内容来确定将哪个文本文件嵌入到外部文本文件中?

4

3 回答 3

1

如果您在编辑文件('chmod +x 编辑文件')上设置了 +x 位,那么您可以执行以下操作:

g/include/s//cat/\
.w\
d\
r !%
w
q

说明

g/include/s//cat/\

启动全局命令。

.w\

(从全局上下文中),仅用当前行覆盖编辑文件(有效地:'cat included_file',您将包含的文件替换为有问题的文件名。)

d\

(从全局上下文中),从缓冲区中删除当前行。(即删除'include included_file',再次,included_file 代表有问题的文件)。

r !%

(从全局上下文中),读取执行默认文件的输出(这是我们正在编辑的文件,上面被“cat ...”覆盖)。

w

(最后,在全球范围之外)。将缓冲区写入(保存)回编辑文件。

q

退出。

于 2020-02-02T05:14:42.943 回答
0

使用 GNU awk:

awk --load readfile '{if ($1=="INCLUDE") {printf readfile($2)} else print}' outer.txt
于 2018-05-09T19:33:09.527 回答
0

用 gnu sed

sed -E 's/( *)INCLUDE(.*)/printf "%s" "\1";cat \2/e' outer.txt
于 2018-05-09T20:02:05.217 回答