Issue
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.
Solution
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]
Answered By - Ed Morton Answer Checked By - Terry (WPSolving Volunteer)