如何使用 Linux 命令模拟 #include <myFile.txt>

Jon*_*emp 5 text-processing

因此,我尝试从包含其他文件的源文件创建输出文件。

(我的用例实际上是 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或者其他东西可以做到这一点?

mem*_*chr 8

cpp - 可以使用 C 预处理器命令。该命令通常包含在gcccpp软件包中。

尽管它被称为 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标志禁止在预处理器的输出中生成行标记。
  • 手册页
  • 关于“您可以使用标准 C 预处理器指令,例如 #include、#define、#ifdef 等”。- 但如果您不希望这样,而只想按原样包含文件,那么除了将每个 #INCLUDE 转换为 #include 并将包含的文件名用引号引起来之外,您还必须执行某些操作来禁用字符串的任何出现 # include、#define、#ifdef 等可能恰好在运行 cpp 之前出现在您的输入中,否则它会根据出现的这些字符串对您的文本进行不必要的转换。
  • 如果本地目录中缺少要包含的文件(假设您的 cpp 实现确实首先搜索本地目录,通常是这种情况),您也可能会得到意外结果,但 cpp 可以在以下目录之一中找到同名文件:它搜索包含文件的其他实现定义的目录。

  • @EdMorton 感谢您提供信息。您介意编辑这个答案吗? (2认同)