将某些标记替换为文件的内容(使用 bash 脚本)
我有一个包含一些文本以及单词 INSERT_HERE1
和 INSERT_HERE2
的文件。我想分别用 file1.txt
和 file2.txt
的内容替换这些单词。
我怀疑 sed 或 awk 可以成功,但我基本上从未使用过它们。
I have a file containing some text and the words INSERT_HERE1
and INSERT_HERE2
. I'd like to replace these words with the content of file1.txt
and file2.txt
respectively.
I suspect sed
or awk
could pull it off but I've basically never used them.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
Sed 确实有一个内置的读取文件命令。您想要的命令将如下所示:
这将输出
r 命令读取文件,d 命令删除带有
INSERT_HERE
标记的行。由于 sed 命令和多行输入,您需要使用大括号,因为 sed 命令必须在自己的行上开始,并且根据您的 shell,您可能需要在行末尾使用\
来避免过早执行。如果这是您经常使用的东西,您可以将命令放入文件中并使用 sed -f 来运行它。Sed does have a built-in read file command. The commands you want would look something like this:
This would output
The r command reads the file, and the d command deletes the line with the
INSERT_HERE
tags. You need to use the curly braces since sed commands and multi-line input since sed commands have to start on their own line, and depending on your shell, you may need\
at the end of the lines to avoid premature execution. If this is something you would use a lot, you can just put the command in a file and usesed -f
to run it.如果你熟悉 Perl,你可以这样做:
If you are okay with Perl you can do:
这尚未经过测试,但与您需要的非常接近:
不过,它无法正确处理包含斜杠的文件,因此您可能需要稍微调整一下。
不过,我会推荐 Perl。像这样的事情:
假设 INSERT_HERE1 和 INSERT_HERE2 每行只能出现一次,并且
file1.txt
不包含文本 INSERT_HERE2 (不过修复起来并不困难)。像这样使用:This is not tested, but would be pretty close to what you need:
It will not properly handle a file with slashes in it, though, so you may need to tweak it a bit.
I'd recommend Perl instead, though. Something like this:
This assumes that INSERT_HERE1 and INSERT_HERE2 may only appear once per line, and that the
file1.txt
does not include the text INSERT_HERE2 (wouldn't be difficult to fix, though). Use like this:这适用于可能被替换多次的小型替换文件:
您可能需要在各处添加一些额外的换行符,具体取决于您希望输出的外观。
This is suitable for small substitution files that may be substituted many times:
You may want to add some extra newlines here and there, depending on how you want your output to look.
使用 Bash 即可轻松完成。如果您需要它是 POSIX shell,请告诉我:
Easily done with Bash. If you need it to be POSIX shell let me know:
此代码片段替换上面数组中指定的任何部分。例如,这里
包含“insert.txt”的内容
如果您不害怕 .zip 文件,您可以尝试这个示例,只要它在线: http://ablage.stabentheiner.de/2013-04-16_contentreplace.zip
This snippet replaces any section that is specified in the upper array. For e.g. here
with the contents of "insert.txt"
If you're not afraid of .zip files you can try this example as long as it is online: http://ablage.stabentheiner.de/2013-04-16_contentreplace.zip
我将使用 Perl 的就地替换 -i.ext 选项
然后,使用
diff myfile.bak myfile
进行验证:I would use perl's in place replacement with -i.ext option
Then, use
diff myfile.bak myfile
to verify: