Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I want to do a grep for \resources\. How do I do this?

I've tried:

grep \resources\
grep \\resources\\
grep "\resources\"
grep "\\resources\\"

None of these work.

share|improve this question
3  
Use single quotes instead of double quotes to avoid bash's interpretation of the backslashes. grep '\\resources\\' –  Paul Tomblin Feb 9 '12 at 19:59

3 Answers 3

up vote 7 down vote accepted

The backslash is a special character for many applications:

  • including the shell: you need to escape it using another backslash or more elegantly, using single quotes when possible:

    $ /bin/echo foo\\bar 'foo\bar'
      foo\bar foo\bar
    

    Here the command received two arguments with value foo\bar, which were echoed as-is on the terminal.

    (Above I used /bin/echo because, the shell-builtin echo might act differently with some shells)

  • But backslash is aslo a special character for grep which recognize many special sequences \(, \|, \., etc… So similarly you need to feed grep with a double \\ for an actual backslash character. This means that using the shell you need to type:

    grep 'foo\\bar'
    

    or equivalently:

    grep foo\\\\bar
    

    (both lines tell the shell to transmit foo\\bar as argument to grep).

  • Many other commands interpret backslashes in some of their arguments… and two levels of escaping are needed (one to escape the shell interpretation, one to escape the command interpretation).


By the way, for the shell, single quotes '…' prevent any kind of character interpretation, but double quotes only prevents some of them: in particular $ and \ remain active characters within "…".

share|improve this answer

You can also use fgrep (which is just grep with the -F flag). This forces grep to interpret the pattern as a fixed string (i.e. it'll treat a / as a literal /). You'll still need to protect the backslashes from expansion by the shell.

grep -F '\resources\'
share|improve this answer

grep requires four backslashes to represent a backslash:

grep "\\\\resources\\\\"
share|improve this answer
6  
This is a rather misleading oversimplification. grep only requires 1 backslash to escape another backslash, but the shell also requires backslashes to be quoted. Double quotes (") do NOT quote backslashes, but backslash does, which is why the double quotes in your example do nothing and the 4 backslashes are needed instead. –  jw013 Feb 9 '12 at 18:45

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.