How to grep an exact string with slash in it?

谁说胖子不能爱 提交于 2021-02-16 18:24:12

问题


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 slash
  • superman - 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:

  1. | is not special in a basic regex. You either need to escape it or use grep -E
  2. 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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!