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 🙂
Advertisement
Answer
The sed expression you are looking for is something like this:
sed -e '/CCCCC/{N;s/CCCCCnDDDDD/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/CCCCCnDDDDDnBBBBB/KKKKK/}'