Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep to find literal [square brackets] with specific data

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.

like image 375
Kavish Gour Avatar asked Oct 11 '25 10:10

Kavish Gour


2 Answers

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]
like image 128
Cyrus Avatar answered Oct 13 '25 23:10

Cyrus


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]
like image 43
Ed Morton Avatar answered Oct 14 '25 00:10

Ed Morton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!