用文件.txt的内容替换多行字符串

用文件.txt的内容替换多行字符串

我对这个问题进行了大量研究,但提出的解决方案都没有用。我有两个文件,alpha(没有扩展名,它是一个 openfoam 词典)和 beta.txt。我将用 beta.txt 的内容替换 alpha 中的字符串块。alpha 的内容如下:

Some text which must not be changed
Some text which must not be changed
Some text which must not be changed
Some text which must not be changed
Amin     0.3;
Bmin     0.1;
Cmin     0.4;
vertices
Some text which must not be changed
Some text which must not be changed
Some text which must not be changed
Some text which must not be changed

beta的内容为:

Amin     0.7;
Bmin     0.4;
Cmin     0.1;
vertices

我会永久编辑通过将 beta 块替换为 Amin ... vertices 来修改文件 alpha(不仅在终端中),alpha 和 beta 的数值都可以改变,但名称“Amin”、“Bmin”、“Cmin”和“vertices”是恒定的。我尝试过 perl 如下:

perl -i -p0e 's/Amin.*?vertices\n/`cat beta.txt`/se' alpha.txt

但它不起作用。请注意,没有新行、制表符和分号。可能没有包括在内。提前谢谢您!

答案1

您的命令对我有用。尝试运行以export LC_ALL=C消除任何语言问题。并添加-w到您的perl命令以打开警告。检查在之后没有空格verticesalpha.txt您可能需要对您的输入进行十六进制转储:xxd alpha.txt以检查可能阻止您的正则表达式匹配的不可见字节,例如@steeldriver建议的回车符。

如果你使用-i(就地替换)运行,但将输出发送到 stdout,您可以根据需要将其重定向到其他文件。这样,如果出现问题,您可以更轻松地重复测试。一旦命令正常运行,您就可以添加-i回来。

以下是我运行的内容:

$ cat tt
cat alpha.txt
echo
export LC_ALL=C
perl -wp0e 's/Amin.*?vertices\n/`cat beta.txt`/se' alpha.txt

这是我的输出

$ tt
Some text which must not be changed
Some text which must not be changed
Some text which must not be changed
Some text which must not be changed
Amin     0.3;
Bmin     0.1;
Cmin     0.4;
vertices
Some text which must not be changed
Some text which must not be changed
Some text which must not be changed
Some text which must not be changed

Some text which must not be changed
Some text which must not be changed
Some text which must not be changed
Some text which must not be changed
Amin     0.7;
Bmin     0.4;
Cmin     0.1;
vertices
Some text which must not be changed
Some text which must not be changed
Some text which must not be changed
Some text which must not be changed

顺便说一句,你一定做过很多经过大量研究才得出你的命令。这个命令比我预期的第一次提问者要高级得多。

相关内容