问题描述
将 $
放在方括号内对 grep 不起作用.
~ $ echo -e "hello
there" >例子.txt~ $ grep "hello$" example.txt你好~ $ grep "hello[$]" example.txt~$
这是 grep 中的错误还是我做错了什么?
这就是它应该做的.
[$]
...定义一个匹配一个字符的字符类,$
.
因此,这将匹配包含 hello$
的行.
见规范要求如此.引用完整定义:
括号表达式(用方括号括起来的表达式,[]")是一个 RE,它应匹配括号表达式表示的非空整理元素集中包含的单个整理元素.
因此,任何括号表达式都匹配单个元素.
此外,在
- 美元符号 ( '$' ) 在用作整个 BRE 的最后一个字符时应作为锚点.当用作子表达式的最后一个字符时,实现可以将美元符号视为锚点.美元符号应将表达式(或可选的子表达式)锚定到匹配字符串的末尾;美元符号可以说是匹配最后一个字符之后的字符串结尾.
因此——从 BRE 开始,grep
默认识别的正则表达式格式不带参数——如果 $
不在表达式的末尾,它是不需要被识别为锚点.
Putting $
inside square brackets doesn't work for grep.
~ $ echo -e "hello
there" > example.txt
~ $ grep "hello$" example.txt
hello
~ $ grep "hello[$]" example.txt
~ $
Is this a bug in grep or am I doing something wrong?
That's what it's supposed to do.
[$]
...defines a character class that matches one character, $
.
Thus, this would match a line containing hello$
.
See for the formal specification requiring that this be so. Quoting from that full definition:
Thus, any bracket expression matches a single element.
Moreover, in
Thus -- as of BRE, the regexp format which grep
recognizes by default with no arguments -- if $
is not at the end of the expression, it is not required to be recognized as an anchor.
这篇关于行尾字符 ($) 在方括号内不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!