How to grep an exact string with slash in it?

Viewed 531

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?

2 Answers

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.
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.

Related