我想包含一个文件,并缩进所有行。我希望它成为降价文档中的代码块。
基本上我想要这样的东西:
text
include(somefile)
text
具有以下输出:
text
content
from
somefile
text
我翻阅了manual,发现了patsubst
。我也找到了这个问题和答案:How to indent a block of text in an m4 macro
适用于不包含逗号的文件:
$ cat textnocomma
some text.
with sentences.
and no commas.
$ cat patsubstincludenocomma
text
patsubst(include(textnocomma), `^', ` ')
text
$ m4 patsubstincludenocomma
text
some text.
with sentences.
and no commas.
text
但是当我include
包含逗号的文件时:
$ cat textcomma
some text.
with sentences.
and, commas.
$ cat patsubstincludecomma
text
patsubst(include(textcomma), `^', ` ')
text
$ m4 patsubstincludecomma
text
m4:patsubstincludecommanoquote:3: Warning: excess arguments to builtin `patsubst' ignored
some text.
with sentences.
and
text
问题似乎是m4进行宏扩展的幼稚方式。包含的文本中的逗号被解释为patsubst
宏的语法。解决方案(应该是简单的):引用包含的文本。
但是,如果我引用include
,则仅缩进第一行:
$ cat patsubstincludecommaquote
text
patsubst(`include(textcomma)', `^', ` ')
text
$ m4 patsubstincludecommaquote
text
some text.
with sentences.
and, commas.
text
我尝试了引号和文字换行符的不同组合,而不是正则表达式换行符。但是到目前为止,我所得到的只是excess arguments
错误消息,或者只是缩进的第一行。
如何包含带有逗号的文本以及其他m4语法,并使其缩进m4?
答案 0 :(得分:2)
为什么不使用外部命令?
esyscmd(`sed "s,^, ," textcomma')
答案 1 :(得分:2)
我已经进行了一些研究,可以得出这样的结论:用引号include
使patsubst
在文本的第一行之外不再识别^
(行首)。至少在我的系统上。
$ m4 --version
m4 (GNU M4) 1.4.18
...
观察:
$ cat textnocomma
some text.
with sentences.
and no commas.
$ cat includenocomma
foo
patsubst(include(textnocomma), `^', ` ')
bar
patsubst(`include(textnocomma)', `^', ` ')
baz
$ m4 includenocomma
foo
some text.
with sentences.
and no commas.
bar
some text.
with sentences.
and no commas.
baz
在将文本定义为“字符串文字”而不是include
时也会发生这种情况:
$ cat definestringliterals
define(`sometext', `first line
second line
third line')dnl
foo
patsubst(sometext, `^', ` ')
bar
patsubst(`sometext', `^', ` ')
baz
$ m4 definestringliterals
foo
first line
second line
third line
bar
first line
second line
third line
baz
以下是支持该观察的问答:How to match newlines in GNU M4 _properly_
奇怪的是,如果将字符串文字直接放在patsubst
中,则不会发生这种情况:
$ cat patsubststringliterals
foo
patsubst(first line
second line
third line, `^', ` ')
bar
patsubst(`first line
second line
third line', `^', ` ')
baz
$ m4 patsubststringliterals
foo
first line
second line
third line
bar
first line
second line
third line
baz
使用括号“引用”文本不存在此问题。但现在我的文字周围有括号:
$ cat textcomma
some text.
with sentences.
and, commas.
$ cat includecomma
foo
patsubst(include(textcomma), `^', ` ')
bar
patsubst(`include(textcomma)', `^', ` ')
baz
patsubst((include(textcomma)), `^', ` ')
qux
$ m4 includecomma
foo
m4:includecomma:2: Warning: excess arguments to builtin `patsubst' ignored
some text.
with sentences.
and
bar
some text.
with sentences.
and, commas.
baz
(some text.
with sentences.
and, commas.
)
qux
所以我想这是一个错误。如果引用include
,则patsubst
将不再识别第一行中的^
。但是,必须使用引号include
来防止文本中的逗号被解释为语法。