简体   繁体   English

使用 shell 脚本替换文件中的多行文本

[英]Replace multiline text in a file using shell script

I want to replace multiple lines of text in a file.我想替换文件中的多行文本。

Example: I want to replace示例:我想替换

Hello
World

With

Hi
Programmer

Can anyone help.任何人都可以帮忙。

Perl to the rescue! Perl 来救援!

perl -p -0777 -e 's/Hello\nWorld/Hi\nProgrammer/g'
  • -0777 enables the slurp mode, ie it reads the whole file as a single block. -0777启用 slurp 模式,即它将整个文件作为单个块读取。 You can also use -00 which enables the paragraph mode: it reads the input in blocks separated by at least two newlines, so unless the text to replace contains two consecutive newlines, you can use this mode, too.您还可以使用-00来启用段落模式:它读取由至少两个换行符分隔的块中的输入,因此除非要替换的文本包含两个连续的换行符,否则您也可以使用此模式。
  • -p for each block, it runs the code and prints the result -p对于每个块,它运行代码并打印结果

Using this command you can accomplish your task.使用此命令,您可以完成任务。 sed -i 's/Hello\nWorld/Hi\nProgrammer/g' your_file.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM