Using grep command for absolute results

Posted on

Problem :

If we use the grep command with '<string>' the result will be absolute. For example:

File1:

test
test2
1test

If we use cat File1 | grep test the output will be:

test 
test2 
1test

But if we want to get only first row we must grep '<test>'.

Here it is the question: How can use these chars with a variable in script? Example:

cat file1 | grep '/<$1/>'

But this command does not work.

Solution :

Single quotes do not allow variable expansion. Thus, '$1' will be a literal $1. Instead, you want double quotes. See this wiki entry about quotes for more.

$ foo=test
$ grep "<$foo>" file1
test

Note that < and > can also be replaced with word boundaries:

$ grep "b$foob" file1
test    

You also don’t need to cat a file to grep – it can read a file on its own.

You are looking for -w to match words:

$ grep -w 'test' File1
test

In case you have the info in a variable, just use it normally with double quotes as slhck already explained:

$ var="test"
$ grep -w "$var" File1
test

From man grep:

-w
–word-regexp

Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified.

Leave a Reply

Your email address will not be published. Required fields are marked *