如何使用 sed 用另一个文件的内容替换一个文件中的模式? [英] How to replace a pattern in one file, with the contents of another file, using sed?

查看:44
本文介绍了如何使用 sed 用另一个文件的内容替换一个文件中的模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有 fileA,包含内容

Hello, this is some
random text REPLACEHERE and some more
random text

fileB 与内容

stuff that goes into
fileA, at that specific place

如何用 fileB 的内容正确替换 fileA 中的 REPLACEHERE ?就在那个地方,就像我在做一个简单的正则表达式操作一样?

How do I properly replace REPLACEHERE inside fileA, with the contents of fileB ? Exactly in that place, just as if I was doing a simple regex operation ?

我得到的最接近的是

sed -i '/REPLACEHERE/r fileB' fileA

它只会在找到 REPLACEHERE 之后将 fileB 附加到行中,这是不好的.我需要将它完全替换到位(我认为这实际上是 i 标志的用途).

which only ends up appending fileB in the line after REPLACEHERE was found, and that's no good. I need it to be replaced exactly in place (I thought that's what the i flag was for actually).

推荐答案

仅使用 sed 可能不会那么容易,我会使用 shell 变量/命令扩展:

It probably won't be that easy with sed only, I'd use a shell variable/command expansion:

sed -i "s/REPLACEHERE/$(cat fileB)/g" fileA

-i 表示更改将保存到 fileA,而不是打印到 stdout.

-i means that the changes will be saved to fileA, rather than printed to stdout.

顺便提一下fileB 中的斜线.如果有的话,他们将不得不逃脱.

Mind the slashes in fileB, by the way. If there are any, they will have to be escaped.

这篇关于如何使用 sed 用另一个文件的内容替换一个文件中的模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆