sed: Find start of pattern and extract text to end of line, including the pattern

This is my first post, please be nice. I have tried to google and read different tutorials.

The task at hand is:

Input file input.txt (example)

abc123defhij-E-1234jslo
456ujs-W-abXjklp

From this file the task is to grep the -E- and -W- strings that are unique and write a new file starting with the matched pattern (-E-, -W-)

The end result should look like this:

-E-1234jslo
-W-abXjklp

The closest I have come to do this is using this code:

grep -e '-[EW]-' input.txt | sed 's/.*'-[EW]-'//'

The output looks like this:

1234jslo
abXjklp

The problem is that this doesn't give me the -E- and -W- that is part of the regular expression. I guess I need a way to put in the matched part into the replace part of sed.

Thanks in advance for any help.

sed '/-[EW]-/s/.*-[EW]-\(.*\)/\1/' input.txt

I have done a few modifications to your solution, try this:

grep -e '-[EW]-' input.txt | sed 's/^.*\(-[EW]-\)/\1/'

I don't think it produces the results the OP is after.
Also there's no need to use 'grep' when sed can do the same.

It did the trick, thank you very, very much :slight_smile:

Edit:
Actually the pure sed-version 'fixed' the lines with the matching pattern but also printed out all non matching lines while the version with grep worked perfectly

sorry - try this:

sed -n '/-[EW]-/s/.*-[EW]-\(.*\)/\1/p' input.txt