Monday, November 1, 2021

[SOLVED] How to make 'grep' use text and regex at same time?

Issue

I have a bash script where I'm using grep to find text in a file. The search-text is stored in a variable.

found=$(grep "^$line$" "$file")

I need grep to use regex while not interpret the variable $line as regex. If for example $line contains a character which is a regex operator, like [, an error is triggered:

grep: Unmatched [

Is it somehow possible to make grep not interpret the content of $line as regex?


Solution

You can use the -F flag of grep to make it interpret the patterns as fixed strings instead of regular expressions.

In addition, if you want the patterns to match entire lines (as implied by your ^$line$ pattern), you can combine with the -x flag.

So the command in your post can be written as:

found=$(grep -Fx "$line" "$file")


Answered By - janos