End of line char ($) doesn't work inside square brackets

前端 未结 3 1497
一向
一向 2021-01-12 21:29

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

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


        
相关标签:
3条回答
  • 2021-01-12 22:09

    You can, however, use $ in a parenthesis grouping, which facilitates the use of | (or), which can accomplish the same idea as a square bracket group.

    Something like the following might be of interest to you:

    ~ $ cat example.txt 
    hello
    there
    helloa
    hellob
    helloc
    
    ~ $ grep "hello\($\|[ab]\)" example.txt
    hello
    helloa
    hellob
    
    0 讨论(0)
  • 2021-01-12 22:19

    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.

    0 讨论(0)
  • 2021-01-12 22:21

    If you're trying to match end of line characters or the end of the string, you can use (|) like so "ABC($|\n)".

    0 讨论(0)
提交回复
热议问题