How can I use grep for a value from a shell variable?

I am trying to smooth out the exact "variable" shell using word boundaries,

grep "\<$variable\>" file.txt 

but failed; I tried everything else but did not succeed.

Actually I am calling grep from a Perl script:

 $attrval=`/usr/bin/grep "\<$_[0]\>" $upgradetmpdir/fullConfiguration.txt` 

$_[0] and $upgradetmpdir/fullConfiguration.txt contain some corresponding "text".

But $attrval empty after the operation.

+4
source share
8 answers

@OP, you have to do this "grepping" in Perl. do not invoke system commands unnecessarily if there is no choice.

 $mysearch="pattern"; while (<>){ chomp; @s = split /\s+/; foreach my $line (@s){ if ($line eq $mysearch){ print "found: $line\n"; } } } 
+4
source

I do not see a problem here:

file.txt:

 hello hi anotherline 

Now,

 mala@human ~ $ export GREPVAR="hi" mala@human ~ $ echo $GREPVAR hi mala@human ~ $ grep "\<$GREPVAR\>" file.txt hi 

What exactly does not work for you?

+1
source

Not every grep supports the syntax of the word ex (1) / vi (1).

I think it's simple:

 grep -w "$variable" ... 
+1
source

Using single quotes for me works in tcsh :

 grep '<$variable>' file.txt 

I assume that your input file contains a literal string: <$variable>

0
source

If variable=foo are you trying to grep for "foo"? If so, this works for me. If you are trying to grep variable named "$ variable", change the quotes to single quotes.

0
source

On the latest linux, it works as expected. Could try egrep

0
source

Say what you have

 $ cat file.txt This line has $variable DO NOT PRINT ME! $variableNope $variable also 

Then with the next program

 #! /usr/bin/perl -l use warnings; use strict; system("grep", "-P", '\$variable\b', "file.txt") == 0 or warn "$0: grep exited " . ($? >> 8); 

you will get a conclusion

  This line has $ variable
 $ variable also 

It uses the -P switch in GNU grep , which matches Perl regular expressions. The function is still experimental, so proceed with caution.

Also note the use of system LIST , which bypasses shell quotation marks, allowing the program to specify arguments with citation rules in Perl rather than with the shell.

You can use the -w (or --word-regexp ), as in

 system("grep", "-w", '\$variable', "file.txt") == 0 or warn "$0: grep exited " . ($? >> 8); 

to get the same result.

0
source

Using a single quote will not work. You have to go double quote

For instance:

 this wont work -------------- for i in 1 do grep '$i' file done this will work -------------- for i in 1 do grep "$i" file done 
0
source

Source: https://habr.com/ru/post/1301464/


All Articles