搜索和替换(多行) [英] Search and Replace ( multiple lines )

查看:61
本文介绍了搜索和替换(多行)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好 StackOverflow 社区!

我正在编写 bash 脚本以在 动态 文本文件中进行更改,我想用一行替换多行.

I'm working on a bash script to change in Dynamic text file, I want to replace multiple lines with one line.

例如:

这个例子,我想替换THIS

CCCCC 
DDDDD

使用KKKKK

脚本之前

AAAAA
CCCCC
DDDDD
BBBBB
CCCCC
DDDDD
CCCCC

脚本之后

AAAAA
KKKKK
BBBBB
KKKKK
CCCCC

我找到了一个使用( sed )替换的脚本,但它不会替换多行.

I found a script to replace using ( sed ) but it doesn't replace multiple lines.

注意:我是编写脚本的初学者,所以请解释如何轻松完成 :)

NOTE: I'm a beginner at scripting so please explain how it can be done easy :)

推荐答案

您正在寻找的 sed 表达式是这样的:

The sed expression you are looking for is something like this:

sed -e '/CCCCC/{N;s/CCCCC\nDDDDD/KKKKK/}'

这是做什么的?

它命令 sed 执行由大括号分隔的命令块,只要与正则表达式 CCCCC 匹配(你可能更喜欢用 ^CCCCC 替换它)$)

It commands sed to execute the command block delimited by braces whenever there is a match to the regex CCCCC (you may prefer to substitute this by ^CCCCC$)

每当执行上述块时,它所做的第一件事就是将下一行添加到模式空间.然后它只是执行一个替换命令.

Whenever the aforementioned block is executed, the first thing it does is add the next line to the pattern space. And then it just performs a substitution command.

另见对这个问题在 UNIX &Linux StackExchange 社区.

请注意更多的N;命令可以向模式空间添加更多行.

Please note more N; command to add more line to the pattern space.

例如:

sed -e '/CCCCC/{N; N; s/CCCCC\nDDDDD\nBBBBB/KKKKK/}'

这篇关于搜索和替换(多行)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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