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 $
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.
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.
Wildcards. If you want to display lines containing the literal dot character, use the -F option to grep.
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.
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}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With