5

I've got problem with removing part of string between two patterns with sed. I've always got last PATTERN-2 in line:

test.txt:

PATTERN-1xxxxPATTERN-2aaa
PATTERN-1xxxxPATTERN-2fffPATTERN-1zzzzPATTERN-2gggPATTERN-1zzzzPATTERN-2
PATTERN-1xxxxPATTERN-2bbb

cmd

sed 's/PATTERN-1.*PATTERN-2//g' test.txt

the result of above is

aaa

bbb

but I would like to have

aaa
fffggg
bbb

Is possible to find PATTERN-2 which is closest to PATTERN-1?

0

5 Answers 5

3

As @steeldriver points out, it is easy if you have non-greedy regexps. If not, you can do it with a loop, like this:

sed ':a;s/PATTERN-2/\n/;s/PATTERN-1.*\n//;ta' test.txt

This works because we know there are no newlines in the middle of any line. It would also work with any other character that does not occur in any line, e.g. §.

1
  • this also work : sed 's/PATTERN-2/\n/g; s/PATTERN-1.*\n//Mg;' Commented Jan 18, 2017 at 14:26
1

If you want to use only sed try like below

sed 's/PATTERN-1[^P]*PATTERN-2//g' test.txt
0

In your example, the .* matches stuff that you want to keep.

You can capture that stuff and replace it back by using:

sed 's/PATTERN-1\(.*\)PATTERN-2/\1/g' test.txt

Everything between the brackets gets stored in the first capture buffer and \1 substitute in the value of that buffer.

0

It's easy in a regex implementations that support a non-greedy qualifier, such as perl's ? For example:

perl -pe 's/PATTERN-1.*?PATTERN-2//g' test.txt
0

"Closest" is not really a sed term. But if there is a reasonable limit to the number of repeats of the sequence PATTERN-1.*PATTERN-2 you can hardcode for that number as follows:

     $ sed -E 's/(PATTERN-1).*(PATTERN-2)(.*)\1.*\2/\3/g;s/PATTERN-1.*PATTERN-2//g' <<"end"
     PATTERN-1xxxxPATTERN-2aaa
     PATTERN-1xxxxPATTERN-2fffPATTERN-1zzzzPATTERN-2gggPATTERN-1zzzzPATTERN-2
     PATTERN-1xxxxPATTERN-2bbb
     end

     aaa
     ggg
     bbb

Note that I use the -E option for extended regex syntax. Also note that in the search expression I use backreferences for the PATTERN-1 and -2 strings, just for your comfort.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.