行尾字符($)在方括号内不起作用 [英] End of line char ($) doesn't work inside square brackets

查看:94
本文介绍了行尾字符($)在方括号内不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$放在方括号内不适用于grep.

~ $ echo -e "hello\nthere" > example.txt
~ $ grep "hello$" example.txt 
hello
~ $ grep "hello[$]" example.txt 
~ $ 

这是grep中的错误还是我做错了什么?

解决方案

这就是应该做的.

[$]

...定义与一个字符$匹配的字符类.

因此,这将匹配包含hello$的行.


有关正式的信息,请参见 POSIX RE括号表达式定义要求是这样的规范.引用完整的定义:

方括号表达式(用方括号括起来的表达式"[]")是一个RE,它必须与由方括号表达式表示的一组非空排序规则元素中包含的单个排序规则元素匹配.

因此,任何括号表达式都匹配单个元素.


此外,在 BRE锚定表达式定义中:

  1. 在用作整个BRE的最后一个字符时,美元符号('$')应该是锚点.当用作子表达式的最后一个字符时,该实现可以将美元符号视为锚点.美元符号应将表达式(或可选的子表达式)锚定在要匹配的字符串的末尾;可以说美元符号与最后一个字符后的字符串结尾匹配.

因此-从BRE开始,grep默认不带参数的正则表达式格式-如果$不在表达式的末尾,则不需要将其识别为锚. /p>

Putting $ inside square brackets doesn't work for grep.

~ $ echo -e "hello\nthere" > 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 the POSIX RE Bracket Expression definition for the formal specification requiring that this be so. Quoting from that full definition:

A bracket expression (an expression enclosed in square brackets, "[]" ) is an RE that shall match a single collating element contained in the non-empty set of collating elements represented by the bracket expression.

Thus, any bracket expression matches a single element.


Moreover, in the BRE Anchoring Expression definition:

  1. A dollar sign ( '$' ) shall be an anchor when used as the last character of an entire BRE. The implementation may treat a dollar sign as an anchor when used as the last character of a subexpression. The dollar sign shall anchor the expression (or optionally subexpression) to the end of the string being matched; the dollar sign can be said to match the end-of-string following the last character.

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.

这篇关于行尾字符($)在方括号内不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆