假设我有3个文件:
index.html
And here is foo:
<!-- include: includes/foo.html -->
This can be done similarly:
<code>
<!-- include: includes/bar.txt -->
</code>
includes/foo.html
FOO CONTENTS
FOO CONTENTS
FOO CONTENTS
includes/bar.txt
BAR CONTENTS
BAR CONTENTS
BAR CONTENTS
BAR CONTENTS
BAR CONTENTS
如何使用include
类似命令自动替换 sawk 'some magic code' index.html > compiled.html
?
compiled.html
And here is foo:
FOO CONTENTS
FOO CONTENTS
This can be done similarly:
<code>
BAR CONTENTS
BAR CONTENTS
BAR CONTENTS
BAR CONTENTS
BAR CONTENTS
</code>
补充评论
- 如果未找到此类文件,则应出现警告或错误(首选)(
<!-- include: includes/does-not-exist.txt -->
) - 该
<!-- include: ... -->
行不得位于compiled.html
- 我对
include
语法很灵活。如果更容易的话可能是这样<include "includes/foo.html">
。 - 我想要类似“指针文件",但没有硬编码的文件名,也没有包含指针文件行
- 该命令不应要求我手动指定所有
include
s。 (awk 'some magic code' index.html includes/foo.html includes/bar.txt > compiled.html
不允许) - 它只需要处理大多数文件名,并且不需要太多工具(例如,我宁愿不安装 PHP 服务器只是为了使用
<? include "includes/bar.txt" ?>
)
答案1
和perl
:
perl -0777 -pe 'while (s{<!-- include: (.*?) -->}{
open I, "<", $1; <I>}ge) {}' index.html > compiled.html
(while
使其递归以允许包含更多文件的循环)。
这捕获组 (.*?)
允许检索文件名以将它们包含在文件中F
并H
以$1
.
带有错误处理:
perl -0777 -pe '
while (
s{<!-- include: (.*?) -->}{
if (open I, "<", $1) {
<I>;
} else {
warn "$1: $!\n";
$ret = 1;
"<!-- failed-include: $1 -->"
}
}ge
) {}
END {exit $ret}' index.html > compiled.html