2

My file contains the following lines:

hello_400 [200]
world_678 [201]
this [301]
is [302]
your [200]
friendly_103 [404]
utility [200]
grep [200]

I'm only looking for lines that ends with [200]. I did try escaping the square brackets with the following patterns:

  • cat file | grep \[200\]
  • cat file | grep \\[200\\]$

and the results either contain all of the lines or nothing. It's very confusing.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
Kavish Gour
  • 183
  • 8
  • Your last command `cat file | grep \\[200\\]$` shloud work with `sh`, `bash` and `dash`. – Cyrus Sep 19 '21 at 07:42

2 Answers2

2

I suggest to escape [ and ] and quote complete regex with single quotes to prevent your shell from interpreting the regex.

grep '\[200\]$' file

Output:

hello_400 [200]
your [200]
utility [200]
grep [200]
Cyrus
  • 84,225
  • 14
  • 89
  • 153
1

Always use quotes around strings in shell unless you NEED to remove the quotes for some reason (e.g. filename expansion), see https://mywiki.wooledge.org/Quotes, so by default do grep 'foo' instead of grep foo. Then you just have to escape the [ regexp metacharacter in your string to make it literal, i.e. grep '\[200]' file.

Instead of using grep and having to escape regexp metachars to make them behave as literal though, just use awk which supports literal string comparisons on specific fields:

$ awk '$NF=="[200]"' file
hello_400 [200]
your [200]
utility [200]
grep [200]

or across the whole line:

$ awk 'index($0,"[200]")' file
hello_400 [200]
your [200]
utility [200]
grep [200]
Ed Morton
  • 188,023
  • 17
  • 78
  • 185