codeObjC codeObjC - 2 months ago 24
Bash Question

Using sed for extracting substring from string

I just started using sed from doing regex. I wanted to extract

XXXXXX
from
*****/XXXXXX>
so I was following

sed -n "/^/*/(\S*\).>$/p"


If I do so I get following error


sed: 1: "/^//(\S).>$/p": invalid command code *


I am not sure what am I missing here.

Answer

Try:

$ echo '*****/XXXXXX>' | sed 's|.*/||; s|>.*||'
XXXXXX

The substitute command s|.*/|| removes everything up to the last / in the string. The substitute command s|>.*|| removes everything from the first > in the string that remains to the end of the line.

Or:

$ echo '*****/XXXXXX>' | sed -E 's|.*/(.*)>|\1|'
XXXXXX

The substitute command s|.*/(.*)>|\1| captures whatever is between the last / and the last > and saves it in group 1. That is then replaced with group 1, \1.

Comments