When grep “\\” XXFile I got “Trailing Backslash”

后端 未结 2 1888
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-31 01:25

Now I want to find whether there are lines containing \'\\\' character. I tried grep \"\\\\\" XXFile but it hints \"Trailing Backslash\". But when I tried gre

相关标签:
2条回答
  • 2021-01-31 02:05

    The difference is in how the shell treats the backslashes:

    • When you write "\\" in double quotes, the shell interprets the backslash escape and ends up passing the string \ to grep. Grep then sees a backslash with no following character, so it emits a "trailing backslash" warning. If you want to use double quotes you need to apply two levels of escaping, one for the shell and one for grep. The result: "\\\\".

    • When you write '\\' in single quotes, the shell does not do any interpretation, which means grep receives the string \\ with both backslashes intact. Grep interprets this as an escaped backslash, so it searches the file for a literal backslash character.

    If that's not clear, we can use echo to see exactly what the shell is doing. echo doesn't do any backslash interpretation itself, so what it prints is what the shell passed to it.

    $ echo "\\"
    \
    $ echo '\\'
    \\
    
    0 讨论(0)
  • You could have written the command as

    grep "\\\\" ...
    

    This has two pairs of backslashes which bash will convert to two single backslashes. This new pair will then be passed to grep as an escaped backslash getting you what you want.

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