Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shell variable in a grep regex

Tags:

grep

bash

I'm trying to use a variable in a grep regex. I'll just post an example of the failure and maybe someone can suggest how to make the variable be evaluated while running the grep command. I've tried ${var} as well.

$ string="test this" $ var="test" $ echo $string | grep '^$var' $  

Since my regex should match lines which start with "test", it should print the line echoed thru it.

$ echo $string test this $ 
like image 689
mike_b Avatar asked Aug 09 '13 13:08

mike_b


People also ask

Can you use regex with grep?

GNU grep supports three regular expression syntaxes, Basic, Extended, and Perl-compatible. In its simplest form, when no regular expression type is given, grep interpret search patterns as basic regular expressions. To interpret the pattern as an extended regular expression, use the -E ( or --extended-regexp ) option.

How do you grep for a variable?

You can use the wc utility to count the number of times a string is found in a variable. To do this, you must first tell grep to only show the matching characters with the -o (--only-matching) option. Then you can pipe it to wc.

Can you use wildcards with grep?

Wildcards. If you want to display lines containing the literal dot character, use the -F option to grep.

How do you grep special characters?

To match a character that is special to grep –E, put a backslash ( \ ) in front of the character. It is usually simpler to use grep –F when you don't need special pattern matching.


1 Answers

You need to use double quotes. Single quotes prevent the shell variable from being interpolated by the shell. You use single quotes to prevent the shell from doing interpolation which you may have to do if your regular expression used $ as part of the pattern. You can also use a backslash to quote a $ if you're using double quotes.

Also, you may need to put your variable in curly braces ${var} in order to help separate it from the rest of the pattern.

Example:

$ string="test this" $ var="test" $ echo $string | grep "^${var}" 
like image 66
David W. Avatar answered Sep 22 '22 23:09

David W.