3

When running the following

echo "abc>asf<tfg"|sed 's/.*>\(.*\)</\1/'

The output is:

asftfg

I don't understand why tfg gets printed? My expected result is asf. Though, it works fine in the following.

expr `echo "abc>asf<tfg"`  : '.*>\(.*\)<'

Which gets me:

asf

And help me to extract the string between > and < when input is being received from a pipe.

1
  • This question title could use some work. Apr 25, 2020 at 7:10

1 Answer 1

2

The s command in sed is a match-and-replace. In your case, .*>\(.*\)< is the pattern to be matched, and \1 is the template to replace it with.

When you try to find a match for .*>\(.*\)< at the beginning of abc>asf<tfg, the result is abc>asf<. This part of the string is then replaced with asf. tfg was not matched, so nothing happens to it.

Using .*>\(.*\)<.* as your match pattern should get you the results you want.

1
  • You can also cheat with awk like this: echo "abc>asf<tfg"|awk -F'<|>' '{print $2}'
    – Yaron
    Nov 15, 2015 at 10:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .