Why does grep match all lines for the pattern “\'”

后端 未结 4 708
挽巷
挽巷 2021-01-12 04:31

In this SO question there is something that I cannot explain:

grep \"\\\'\" input_file

matches all lines in the given file. Does \\\'

相关标签:
4条回答
  • 2021-01-12 04:38

    grep regex GNU extension: ‘\'’ matches the end of the whole input

    0 讨论(0)
  • 2021-01-12 04:51

    That is a really strange beaviour of grep, I don't know how to explain it, but I must note that \' doesn't match any character. It looks like it has the same meaning as $:

    $ echo x | grep "x\'"
    x
    $ echo xy | grep "x\'"
    $ echo x | grep "\'x"
    

    Update 1

    As it is stated in http://www.gnu.org/software/findutils/manual/html_node/find_html/grep-regular-expression-syntax.html (thanks to Richard Sitze for the link) it really has the same meaning as $. But meanwhile I've noted a difference between \' and $:

    $ echo x | grep 'x$'
    x
    $ echo x | grep 'x$$'
    $ echo x | grep "x\'"
    x
    $ echo x | grep "x\'\'"
    x
    $ echo x | grep "x\'\'\'"
    x
    

    You can specify \' as many times as you wish but that is not so for $. There must be only one $.

    Another important remark. The manual says:

     ‘\'’ matches the end of the whole input
    

    But strictly speaking that's not truth because \' matches not only the end of the whole input but the end of every single line also:

    $ (echo x; echo y) | grep "\'"
    x
    y
    

    Exactly how $ does.

    0 讨论(0)
  • 2021-01-12 04:53

    \ is an escape character. This mean the the ' should considered as text to search for, and not as a control character.

    0 讨论(0)
  • 2021-01-12 04:54

    I did not know this feature of the regular expressions. But it's listed at regular-expressions.info as the end of the string anchor.

    It does not exist in all regex implementations only in GNU Basic and Extended Regular Expressions, see this compatibility chart for more info.

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