问题
I'm running macOS.
There are the following strings:
/superman
/superman1
/superman/batman
/superman2/batman
/superman/wonderwoman
/superman3/wonderwoman
/batman/superman
/batman/superman1
/wonderwoman/superman
/wonderwoman/superman2
I want to grep only the bolded words.
I figured doing grep -wr 'superman/|/superman' would yield all of them, but it only yields /superman.
Any idea how to go about this?
回答1:
You may use
grep -E '(^|/)superman($|/)' file
See the online demo:
s="/superman
/superman1
/superman/batman
/superman2/batman
/superman/wonderwoman
/superman3/wonderwoman
/batman/superman
/batman/superman1
/wonderwoman/superman
/wonderwoman/superman2"
grep -E '(^|/)superman($|/)' <<< "$s"
Output:
/superman
/superman/batman
/superman/wonderwoman
/batman/superman
/wonderwoman/superman
The pattern matches
(^|/)
- start of string or a slashsuperman
- a word($|/)
- end of string or a slash.
回答2:
grep '/superman\>'
\>
is the "end of word marker", and for "superman3", the end of word is not following "man"
The problems with your -w
solution:
|
is not special in a basic regex. You either need to escape it or usegrep -E
read the man page about how
-w
works:The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character
In the case where the line is
/batman/superman
,- the pattern
superman/
does not appear - the pattern
/superman
is:- at the end of the line, which is OK, but
- is prededed by the character "n" which is a word constituent character.
- the pattern
grep -w superman
will give you better results, or if you need to have superman preceded by a slash, then my original answer works.
来源:https://stackoverflow.com/questions/56688546/how-to-grep-an-exact-string-with-slash-in-it