问题
Two commands below :
grep ', \\.' enrolments
grep ', \.' enrolments
got the same result as shown below
COMP4001|4368523|Doddau Yobhazravi, . |8684 |M
COMP9315|4368523|Doddau Yobhazravi, . |8684 |M
COMP9321|4368523|Doddau Yobhazravi, . |8684 |M
COMP9331|4368523|Doddau Yobhazravi, . |8684 |M
COMP3121|4896558|Vozaila, . |3978/3|F
COMP9321|4896558|Vozaila, . |3978/3|F
COMP9031|4389601|Yiehil, . |8680/2|M
COMP9318|4389601|Yiehil, . |8680/2|M
What are the difference between double backslash and single slash in reg for .?
回答1:
I suspect that you actually used double quotes rather than single quotes in your shell command.
In shell, ", \."
and ", \\."
are exactly the same string. They are also the same as ', \.'
. But ', \\.'
is different.
In a double-quoted string, only a few characters can be escaped using a backslash. Any other use of the backslash is considered a normal character. Since .
is not one of the characters (they are $ ` \ " and the newline character), the \ in \.
is not considered special. On the other hand, the first \ in \\
is treated as an escape character, so it escapes the second \. Either way, you end up with \ ..
In a single-quoted string, the backslash character is never treated as special. It is always treated as just an ordinary character.
Consequently:
$ echo "\." "\\." '\.' '\\.'
\. \. \. \\.
So if you used double quotes, the two commands
grep ", \\." enrolments
grep ", \." enrolments
actually do exactly the same thing, and that has nothing to do with grep
. In both cases, the pattern passed to grep is , \.
. grep
then interprets the backslash character as making the . an ordinary pattern character rather than a wildcard.
However, grep ', \\.' enrolments
would pass the pattern , \\.
to grep
, which will be interpreted as searching for the sequence , SP \ followed by any character. That won't be matched by any of the sample lines you present, since none of them contain a literal backslash.
来源:https://stackoverflow.com/questions/38626697/what-are-the-difference-between-double-backslash-and-single-slash-in-reg-for