$ cat file
anna
amma
kklks
ksklaii
$ grep '\`' file
anna
amma
kklks
ksklaii
Why? How is that match working ?
This appears to be a GNU extension for regular expressions. The backtick ('\\`') anchor matches the very start of a subject string, which explains why it is matching all lines. OS X apparently doesn't implement the GNU extensions, which would explain why your example doesn't match any lines there. See http://www.regular-expressions.info/gnu.html
If you want to match an actual backtick when the GNU extensions are in effect, this works for me:
grep '[`]' file
twm's answer provides the crucial pointer, but note that it is the sequence \\`
, not `
by itself that acts as the start-of-input anchor in GNU regexes .
Thus, to match a literal backtick in a regex specified as a single-quoted shell string , you don't need any escaping at all , neither with GNU grep
nor with BSD/macOS grep
:
$ { echo 'ab'; echo 'c`d'; } | grep '`'
c`d
When using double-quoted shell strings - which you should avoid for regexes , for reasons that will become obvious - things get more complicated, because you then must escape the `
for the shell's sake in order to pass it through as a literal to grep
:
$ { echo 'ab'; echo 'c`d'; } | grep "\`"
c`d
Note that, after the shell has parsed the "..."
string, grep
still only sees `
.
To recreate the original command with a double-quoted string with GNU grep
:
$ { echo 'ab'; echo 'c`d'; } | grep "\\\`" # !! BOTH \ and ` need \-escaping
ab
c`d
Again, after the shell's string parsing, grep
sees just \\`
, which to GNU grep
is the start-of-the-input anchor, so all input lines match.
grep
processes input line by line, \\`
has the same effect as ^
the start-of-a- line anchor; with multi-line input, however - such as if you used grep -z
to read all lines at once - \\`
only matches the very start of the whole string. To BSD/macOS grep
, \\`
simply escapes a literal `
, so it only matches input lines that contain that character.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.