user1810087
user1810087

Reputation: 5334

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

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?

Upvotes: 0

Views: 136

Answers (2)

James Brown
James Brown

Reputation: 37394

Way to tell grep that the characters provided are ordinary characters is to escape them properly, for example:

$ cat file
this
[that
not[
$ line=\\[          # escaped to mark [ as an ordinary character
$ grep "$line" file
that[
[not
$ line=[is]         # [ is part of a proper regex 
$ grep "$line" file
this

So the key is to escape the regex chars:

$ line=[
$ echo "${line/[/\\[}"
\[
$ grep "^${line/[/\\[}" file
[that

Or you could use awk:

$ line=[that
$ awk -v s="$line" '$0==s' file
[that

Upvotes: 0

janos
janos

Reputation: 124648

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")

Upvotes: 6

Related Questions