Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to replace all lines between two points and subtitute it with some text in sed

Tags:

linux

sed

Suppose I have this text:

BEGIN
hello
world
how
are
you
END

How to convert it to bellow text using sed command in linux:

BEGIN
fine, thanks
END
like image 211
Billy The Bob Avatar asked Mar 03 '11 09:03

Billy The Bob


People also ask

How do I use sed to find and replace text in a file?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace.

Which sed command is used to modify all text matches in a line of text?

'g' option is used in `sed` command to replace all occurrences of matching pattern. Create a text file named python.

Which sed command is used for replacement?

The s command (as in substitute) is probably the most important in sed and has a lot of different options. The syntax of the s command is ' s/ regexp / replacement / flags '.


1 Answers

$ cat file
BEGIN
hello
world
how
are
you
END

$ sed -e '/BEGIN/,/END/c\BEGIN\nfine, thanks\nEND' file
BEGIN
fine, thanks
END

/BEGIN/,/END/ selects a range of text that starts with BEGIN and ends with END. Then c\ command is used to replace the selected range with BEGIN\nfine, thanks\nEND.

like image 65
Maxim Egorushkin Avatar answered Sep 23 '22 12:09

Maxim Egorushkin