Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep match exact substring ignoring regex syntax [duplicate]

Tags:

grep

bash

Is there some way to make grep match an exact string, and not parse it as a regex? Or is there some tool to escape a string properly for grep?

$ version=10.4
$ echo "10.4" | grep $version
10.4
$ echo "1034" | grep $version # shouldn't match
1034
like image 203
johv Avatar asked Jul 08 '11 08:07

johv


People also ask

How do you grep with exact match?

To Show Lines That Exactly Match a Search String The grep command prints entire lines when it finds a match in a file. To print only those lines that completely match the search string, add the -x option. The output shows only the lines with the exact match.

Does grep support regex?

The grep understands three different types of regular expression syntax as follows: basic (BRE) extended (ERE) perl (PCRE)

How do you grep a string to exclude?

Exclude Words and Patterns To display only the lines that do not match a search pattern, use the -v ( or --invert-match ) option. The -w option tells grep to return only those lines where the specified string is a whole word (enclosed by non-word characters).

How do you do except in regular expressions?

How do you ignore something in regex? To match any character except a list of excluded characters, put the excluded charaters between [^ and ] . The caret ^ must immediately follow the [ or else it stands for just itself.


1 Answers

Use grep -F or fgrep.

$ echo "1034" | grep -F $version # shouldn't match
$ echo "10.4" | grep -F $version
10.4

See man page:

   -F, --fixed-strings
         Interpret PATTERN as a list of fixed strings, separated
         by newlines, any of which is to be matched.

I was looking for the term "literal match" or "fixed string".

(See also Using grep with a complex string and How can grep interpret literally a string that contains an asterisk and is fed to grep through a variable?)

like image 124
johv Avatar answered Oct 05 '22 05:10

johv