T
T
Tyoma Makeev2015-12-16 17:17:27
Perl
Tyoma Makeev, 2015-12-16 17:17:27

How to replace a string with multiple lines using SED?

Suppose I have a file that has a string containing `123456`
How can I use sed (or whatever) to replace a line in a file containing `123456` with several other lines?
And how can you select several lines, for example 5, if the first contains `123456`, and replace them with one, or also with several lines?
Or maybe not SED, but AWK or Perl? It's not that important, the main thing is that it can work with the file (without any `cat` there), and the syntax was not completely terrible.
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Saboteur, 2015-12-16
@murmuringvoices

What's wrong with line breaks with \n?
sed s/123456/Hello\nWorld/ file.txt
or did I misunderstand the task?
It is unlikely that several lines will be replaced, sed reads the data line by line, so it can be more complicated there, but something like this may work:
sed -i -r "2,5s/.*/# deleted line/g" file.txt
Will clear lines 2 to 5.
sed -i -r "/text1/,/text2/s/.*/# deleted line/g" file.txt
will clear lines between text1 and text2 inclusive (all matches)
sed -i -r " /text1/,+2s/.*/# deleted line/g" file.txt
will clear the line where text1 was encountered and the next two

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question