Home > Enterprise >  REGEX to find and replace multiple line string using SSH
REGEX to find and replace multiple line string using SSH

Time:01-05

Suppose I have a TXT file:

line 1
some text ABC
line 3
line 4
XYZ

I want to remove everything between ABC and XYZ, including those 2 strings, so the result should be

line 1
some text

I use this command

find . -type f -name "*.txt" -exec sed -i '/ABC/,/XYZ/d' {} \;

but it deletes also 'some text' part and the result is

line 1

How to adjust the regex?

It's a modification of this question: Find and replace multiple line string using SSH as the answer there deletes whole lines.

CodePudding user response:

This sed may work for you:

sed '/ABC/,/XYZ/{/ABC/!d; s///;}' file

line 1
some text

Breakdown:

  • /ABC/,/XYZ/: Operate between patterns ABC and XYZ
  • {: Action block start
    • /ABC/!d;: If line doesn't have ABC then delte it
    • s///;: Substitute search pattern ABC with empty string
  • }: Action block end

CodePudding user response:

Using GNU sed

$ sed -Ez 's/ABC.*XYZ//' input_file
line 1
some text
  • Related