Search and Replace ( multiple lines )

拜拜、爱过 提交于 2020-01-16 11:12:30

问题


Hello StackOverflow Community!

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

Ex:

This example, I want to replace THIS

CCCCC 
DDDDD

With KKKKK

Before script

AAAAA
CCCCC
DDDDD
BBBBB
CCCCC
DDDDD
CCCCC

After script

AAAAA
KKKKK
BBBBB
KKKKK
CCCCC

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


回答1:


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

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

What does this do?

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.

See also the answers to this question in the UNIX & Linux StackExchange community.

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

Ex:

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



回答2:


You can do it like this

tr '\n' ' ' < yourText.txt | sed "s/CCCCC DDDDD/KKKKK/g" | tr -s ' ' '\n'

To save it, simply add > another.txt at the end of the above command



来源:https://stackoverflow.com/questions/52018388/search-and-replace-multiple-lines

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