Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When grep "\\" XXFile I got "Trailing Backslash"

Now I want to find whether there are lines containing '\' character. I tried grep "\\" XXFile but it hints "Trailing Backslash". But when I tried grep '\\' XXFile it is OK. Could anyone explain why the first case cannot run? Thanks.

like image 831
dong Avatar asked Dec 03 '13 03:12

dong


People also ask

How do you grep trailing backslash?

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: "\\\\" .

What does backslash mean in grep?

Escaping Special Characters However, sometimes you will need to include an exact, or literal, instance of these characters in your grep pattern. In this case, you must use the backslash character \ before that special character to have it be treated literally; this is known as "escaping" the special character.

How do you escape special characters in grep command?

If you include special characters in patterns typed on the command line, escape them by enclosing them in single quotation marks to prevent inadvertent misinterpretation by the shell or command interpreter. To match a character that is special to grep –E, put a backslash ( \ ) in front of the character.

How do I grep a string with a slash?

The forward slash is not a special character in grep, but may be in tools like sed, Ruby, or Perl. You probably want to escape your literal periods, though, and it does no harm to escape the slash. This should work in all cases: \.


1 Answers

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 '\\' \\ 
like image 113
John Kugelman Avatar answered Oct 04 '22 00:10

John Kugelman