How to replace a pattern in one file, with the contents of another file, using sed?

余生颓废 提交于 2019-12-31 01:57:33

问题


Lets say I have fileA, with the contents

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

and fileB with the contents

stuff that goes into
fileA, at that specific place

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 ?

The closest I've got was

sed -i '/REPLACEHERE/r fileB' fileA

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).


回答1:


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 means that the changes will be saved to fileA, rather than printed to stdout.

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



来源:https://stackoverflow.com/questions/14546949/how-to-replace-a-pattern-in-one-file-with-the-contents-of-another-file-using-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!