bash sed:替换一段文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13043998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:38:11  来源:igfitidea点击:

sed: replace a block of text

bashunixreplacesedawk

提问by jam

I have a bunch of files, starting with a block of code and I'm trying to replace with another.

我有一堆文件,从一段代码开始,我试图用另一个替换。

Replace:

代替:

<?php
$r = session_start();
(more lines)

With:

和:

<?php
header("Location: index.php");
(more lines of code)

So im trying to match the block with sed 's/<?php\n$r = session_start();/<?php\nheader...but it doesn't work.

所以我试图匹配块,sed 's/<?php\n$r = session_start();/<?php\nheader...但它不起作用。

I would appreciate help in what is happening here and how to achieve this. I'm thinking in doing this with python instead.

我很感激这里正在发生的事情以及如何实现这一目标的帮助。我正在考虑用 python 来做这个。

Thanks!

谢谢!

采纳答案by potong

This might work for you (GNU sed):

这可能对你有用(GNU sed):

sed -i '1i\
This is a\
new block of\
code
1,/$r = session_start();/d' file 

Or if you prefer to place the new code in a file:

或者,如果您更喜欢将新代码放在文件中:

sed -i '1r replacement_code_file
1,/$r = session_start();/d' file

All on one line:

全部在一行:

sed -i -e '1r replacement_code_file' -e '1,/$r = session_start();/d' file

回答by Steve

One way using sed:

一种使用方式sed

cat block.txt <(sed '1,/$r = session_start();/d' file.txt) > newfile.txt

Simply add the block of text you'd like to add to each file to block.txt. The sedcomponent simply deletes lines, between the first line and a matching pattern.

只需将要添加到每个文件的文本块添加到block.txt. 该sed组件只是删除第一行和匹配模式之间的行。

回答by Guru

sed, tweaked your solution a little bit:

sed,稍微调整您的解决方案:

sed  '/<?php/{N;s/\n$r = session_start();/\nheader(\"Location: index.php\");/}' file