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

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

问题描述

$ 放在方括号内对 grep 不起作用.

~ $ echo -e "hello
there" >例子.txt~ $ grep "hello$" example.txt你好~ $ grep "hello[$]" example.txt~$

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

解决方案

这就是它应该做的.

[$]

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

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

<小时>

POSIX RE 括号表达式定义规范要求如此.引用完整定义:

<块引用>

括号表达式(用方括号括起来的表达式,[]")是一个 RE,它应匹配括号表达式表示的非空整理元素集中包含的单个整理元素.

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

<小时>

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

<块引用>

  1. 美元符号 ( '$' ) 在用作整个 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 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天全站免登陆