How to make multi-line replacement with sed?

I have a text file called "a6s" with several lines like this:

y
n
yyy
n
y
yyy
yy
y
yyy
n

I used this script:

$ sed -i "s/y$^y/ya\ny/g" a6s;

I want to insert between the two characters "y" at the end of the last line and the beginning of the next line for output:

y
n
yyy
n
ya
yyya
yya
ya
yyy
n
+4
source share
2 answers

Usage GNU sed(full thanks for this wonderful solution belongs to @Sundeep, thanks):

sed -i '/y$/ {N; s/y\ny/ya\ny/; P; D}' a6s

To work on multiple lines with sed, you must use the commands N, Pand D:

  • {cmds}: team group
  • /y$/ {cmds}: executes a group of commands only if the line ends with y
  • N: reads the next line in the pattern space
  • s/regex/replacement/: does replacement do not require flag g
  • P: \n ( )
  • D: \n

, :

sed -i ':a; N; s/y\ny/ya\ny/; {P; D}; ba' a6s

grymoire.com .

+2

sed - , . - , , 1980- , awk. GNU awk multi- char RS:

$ awk -v RS='^$' -v ORS= '{while(sub(/y\ny/,"ya\ny"));} 1' file
y
n
yyy
n
ya
yyya
yya
ya
yyy
n

, - , y\ny ya\ny, y\ny .

+1

Source: https://habr.com/ru/post/1692136/


All Articles