3

the output for the following two commands are same:

echo 'my\name' | grep 'my\\name'
my\name

and also the output for the next command is also same,

echo 'my\name' | grep 'my\\\name'
my\name

Can anyone pls guide why it is resulting in the same output?? Why an extra backslash also not affecting any change in the output?

however, if we increase the number of backslash to four in grep then the output goes away,

echo 'my\name' | grep 'my\\\\name'

no output

Pls guide me with the behavior of grep and backslash in single and double quotes.

frp farhan
  • 445
  • 5
  • 19
  • 1
    superuser.com would be the right place to ask this.... – tod Apr 11 '16 at 09:21
  • 1
    @tod or [unix.se]? – Tom Fenech Apr 11 '16 at 09:23
  • 1
    grep accepts regex's, look up how backslashes behave in regex for an answer(maybe this,http://stackoverflow.com/questions/4025482/cant-escape-the-backslash-with-regex ). If you simply want an exact match though use `grep -F` – 123 Apr 11 '16 at 09:24

1 Answers1

2

In first 2 examples it is matching because \\ in your regex pattern is matching a single \ in input. An extra \ in 2nd example is just escaping n and matching literal n in input.

It will be clear with these examples:

echo 'myname' | grep 'my\name'
myname

echo 'myname' | grep 'myna\me'
myname

echo 'myname' | grep 'm\yn\am\e'
myname

echo 'my\name' | grep 'my\name'

echo 'my\name' | grep 'my\\name'
my\name

echo 'my\name' | grep 'my\\\name'
my\name

echo 'my\name' | grep 'my\\\nam\e'
my\name
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • what if we add double quotes to the regex pattern instead of single quotes then how would the behavior would vary? – frp farhan Apr 11 '16 at 09:43
  • 1
    In double quotes single \ is entered as \\ so you should use: `echo 'my\name' | ggrep "my\\\\name" my\name` – anubhava Apr 11 '16 at 09:49
  • sir what is the nature of backslash in doublequotes of echo statement. From ur comment i understood that in regex used with grep a double backslash is treated as single in double quotes, however what about lhs of pipe if there i use double quotes then hw wud b the behavior pls explain? – frp farhan Apr 12 '16 at 05:51
  • As far as possible use single quote in grep patterns and use double back slash to match a single slash in input. Though keep in mind that variable expansion doesn't happen in single quotes. – anubhava Apr 12 '16 at 07:52