Kavish Gour
Kavish Gour

Reputation: 191

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:

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

Upvotes: 2

Views: 1440

Answers (2)

Ed Morton
Ed Morton

Reputation: 203189

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]

Upvotes: 1

Cyrus
Cyrus

Reputation: 88563

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]

Upvotes: 3

Related Questions