Reputation: 7444
Consider following commands
~ echo "f(ew)" > t
~ egrep "f\([^\)]*\)" t
f(yo)
as expected egrep
matches the whole line.
But for the following commands the regex doesn't catch the last parenthese
~ echo "f(ew)" > t
~ sed -i "s/f\([^\)]*\)/yo/" t
~ cat t
yo)
why isn't the last parenthese catched?
Upvotes: 3
Views: 69
Reputation: 955
Escaping a parenthesis (== normal round brace) within the pattern in sed is part of the special mechanism we use to name the matched string in the substitution string by using \1, \2, etc.
So in your case you don't want sed to interpret your parenthesis as these special characters, but just leave them depict the character they are :) So:
sed -i 's/f([^)]*)/yo/' t
This is the solution brought by konsolebox, but @konsolebox: this is not "quoting/unquoting" that we are talking about, but "escaping" (the characters '(' and ')').
Upvotes: 1
Reputation: 75458
Don't quote it:
sed -i "s/f([^)]*)/yo/" t
Or perhaps use -E
/-r
:
sed -E -i "s/f\([^)]*\)/yo/" t
sed -r -i "s/f\([^)]*\)/yo/" t
-E
or -r
makes it interpret the pattern like egrep
:
-r, --regexp-extended
use extended regular expressions in the script.
Upvotes: 2