因此,我尝试从包含其他文件的源文件创建输出文件。
(我的用例实际上是 Kubernetes/OpenShift 的 YAML,但这些 .txt 文件显示了目标。)
例如:
% cat source.txt
This is the source files it will include two other files.
The first will be here:
#INCLUDE ./first-included-file.txt
And the second file will be inserted here:
#INCLUDE ./second-included-file.txt
And this is the end of source.txt
Run Code Online (Sandbox Code Playgroud)
如果包含的文件是:
% cat first-included-file.txt
This is FIRST
End of FIRST
% cat second-included-file.txt
This is SECOND
End of SECOND
Run Code Online (Sandbox Code Playgroud)
那么输出将是:
This is the source files it will include two other files.
The first will be here:
This is FIRST
End of FIRST
And the second file will be inserted here:
This is SECOND
End of SECOND
And this is the end of source.txt
Run Code Online (Sandbox Code Playgroud)
其他答案使用
sed '/#INCLUDE/ r insertfile'
Run Code Online (Sandbox Code Playgroud)
但是是否有一个通用的解决方案可以从源中的值找到文件名?
我猜想读取并解析每一行的 Bash 脚本可能会完成这项工作,但是也许awk
或者其他东西可以做到这一点?
cpp - 可以使用 C 预处理器命令。该命令通常包含在gcc
或cpp
软件包中。
尽管它被称为 C 预处理器,但它也可以用于其他文件,并且您可以使用标准 C 预处理器指令,例如、#include
等。#define
#ifdef
例如:
源文件.txt
This is the source files it will include two other files.
The first will be here:
#include "first-included-file.txt"
And the second file will be inserted here:
#include "second-included-file.txt"
And this is the end of source.txt
Run Code Online (Sandbox Code Playgroud)
第一个包含文件.txt
This is FIRST
End of FIRST
Run Code Online (Sandbox Code Playgroud)
第二个包含文件.txt
This is SECOND
End of SECOND
Run Code Online (Sandbox Code Playgroud)
的输出cpp -P source.txt
$ cpp -P source.txt
This is the source files it will include two other files.
The first will be here:
This is FIRST
End of FIRST
And the second file will be inserted here:
This is SECOND
End of SECOND
And this is the end of source.txt
Run Code Online (Sandbox Code Playgroud)
笔记:
-P
标志禁止在预处理器的输出中生成行标记。