Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep for expression containing variable

Tags:

bash

I want to add this command grep -co '\b5\b' $INFILE in a bash script. The problem is that instead of 5 i want to use a variable in its place so i write:

V=`grep -co '\b$L\b' $INFILE`

but it does not work since the $ is used to describe internally the end of line in grep. How can i make it work? Is there an escape sequence for $ to make it use its bash meaning of the value of a variable?

like image 963
Fotinopoulos Giorgos Avatar asked Feb 28 '11 13:02

Fotinopoulos Giorgos


People also ask

Can you use grep with a variable?

Grep works well with standard input. This allows us to use grep to match a pattern from a variable. It's is not the most graceful solution, but it works. To learn more about standard streams (STDIN, STDOUT, & STDERR) and Pipelines, read "Linux I/O, Standard Streams and Redirection".

Does grep return a value?

Indeed, grep returns 0 if it matches, and non-zero if it does not. Hence my comment. In the shell 0 means success. Non-zero means failure.

How do you store stdout in a variable?

To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...]

How do you grep a pattern?

To find a pattern that is more than one word long, enclose the string with single or double quotation marks. The grep command can search for a string in groups of files. When it finds a pattern that matches in more than one file, it prints the name of the file, followed by a colon, then the line matching the pattern.


1 Answers

Use " instead of ' to allow expansion of your $L variable.

like image 186
Erik Avatar answered Sep 22 '22 22:09

Erik