在扩展正则表达式(ERE)中,即-r下,$表示行的结尾:
$echo '$foo' | sed -r 's/foo$/bar/'
$bar
如果您希望它表示其他含义,则必须对其进行转义:
$echo '$foo' | sed -r 's/[$]foo$/bar/'
bar
文献资料
man 7 regex解释说,在扩展正则表达式(ERE)中,$与行末匹配:
‘$’ (matching the null string at the end of a line)
相同的手册页继续说明,在没有-r的情况下得到的基本正则表达式(BRE)中,其含义更为复杂:
Obsolete (“basic”) regular expressions differ in several respects.
‘|’, ‘+’, and ‘?’ are ordinary characters and there is no
equivalent for their functionality. The delimiters for bounds are
“{” and “}”, with ‘{‘ and ‘}’ by themselves ordinary characters.
The parentheses for nested subexpressions are “(” and “)”, with ‘(‘
and ‘)’ by themselves ordinary characters. ‘^’ is an ordinary
character except at the beginning of the RE or(!) the beginning of a
parenthesized subexpression, ‘$’ is an ordinary character except at
the end of the RE or(!) the end of a parenthesized subexpression, and
‘*’ is an ordinary character if it appears at the beginning of the
RE or the beginning of a parenthesized subexpression (after a possible
leading ‘^’).