1

Original file looks like this:

BLABLA ABCABC blabl=
a blabla blabla ABC=
ABC blabla blabla A=
BCABC blabla

The result should look like:

BLABLA DEFDEF blabl=
a blabla blabla DEF=
DEF blabla blabla D=
EFDEF blabla

So all ABCABC should be replaced by DEFDEF, even if there is a linebreak (marked with =) in the word.

Is it possible with sed?

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
BP20
  • 55
  • 6
  • Try with Perl: http://stackoverflow.com/questions/3365260/match-and-replace-multiple-newlines-with-a-sed-or-perl-one-liner – Heinz Apr 07 '16 at 09:48

4 Answers4

2

Sed multiline that works for hyphenating ABCABC at an arbitrary position:

$ sed -r 'N;s/A(=\n)?B(=\n)?C(=\n)?A(=\n)?B(=\n)?C/D\1E\2F\3D\4E\5F/g;P;D' infile
BLABLD AEFDEF blabl=
a blabla blabla DEF=
DEF blabla blabla D=
EFDEF blabla

N;P;D is the idiomatic way of keeping two lines at a time in the pattern space. The substitution checks for ABCABC optionally interspersed with = and a newline at any position, and the substitution inserts back what was captured.

This requires extended regular expressions (-E in BSD sed) for the ? operator. GNU sed supports \? in BRE as an extension, though, but all the () would have to be escaped as well.


In case the = just symbolizes a newline and isn't actually there, this simplifies to

$ sed -r 'N;s/A(\n?)B(\n?)C(\n?)A(\n?)B(\n?)C/D\1E\2F\3D\4E\5F/g;P;D' infile
BLABLA DEFDEF blabl
a blabla blabla DEF
DEF blabla blabla D
EFDEF blabla
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
0

Well, it's not multiline, but solves Your example:

sed -r -e 's/ABC/DEF/g' -e 's/AB=/DE=/g' -e 's/A=/D=/g' -e 's/^BC/EF/g' -e 's/^C/F/g' infile
Filip
  • 128
  • 5
0

Try This,

sed -i -e "s/ABC/DEF/g;s/A/D/g;s/B/E/g;s/C/F/g" filename.txt
toxic_boi_8041
  • 1,424
  • 16
  • 26
0

Using gnu awk with null RS you can do this in single replacement (using gensub):

awk -v RS= '{
   print gensub(/A(=\n)?B(=\n)?C(=\n)?A(=\n)?B(=\n)?C/, "D\\1E\\2F\\3D\\4E\\5F", "g", $0)
}' file

Output:

BLABLA DEFDEF blabl=
a blabla blabla DEF=
DEF blabla blabla D=
EFDEF blabla
anubhava
  • 761,203
  • 64
  • 569
  • 643