Bash – sed doesn’t distinguish between full regex match and no match

bashsed

I want to extract portion of a string matching a regex. Consider the following code that works correctly:

regex="ss"
string="blossom"
echo $string | sed "s/^.*\($regex\).*$/\1/"

Output is:

ss

However if the regex matches nothing the whole string is returned.

regex="aa"

Output:

blossom

This is incorrect. When there is no match, nothing should be returned. How can this be accomplished?

Best Answer

As choroba said, sed will always print the line, by default, with any substitutions that matched. You could do what you want with:

regex="ss"
string="blossom"
echo $string | sed -n "s/^.*\($regex\).*$/\1/p"

The -n tells sed not to print the line, then the p at the end of the s/ command tells sed to print the line, with replacements, if it matched anything.

Related Question