How can I grep for a value from a shell variable?
16,918
Solution 1
@OP, you should do that 'grepping' in Perl. don't call system commands unnecessarily unless there is no choice.
$mysearch="pattern";
while (<>){
chomp;
@s = split /\s+/;
foreach my $line (@s){
if ($line eq $mysearch){
print "found: $line\n";
}
}
}
Solution 2
I'm not seeing the 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 isn't working for you?
Solution 3
Not every grep supports the ex(1) / vi(1) word boundary syntax.
I think I would just do:
grep -w "$variable" ...
Author by
Gaurav
Updated on August 21, 2022Comments
-
Gaurav over 1 year
I've been trying to grep an exact shell 'variable' using word boundaries,
grep "\<$variable\>" file.txt
but haven't managed to; I've tried everything else but haven't succeeded.
Actually I'm invoking
grep
from a Perl script:$attrval=`/usr/bin/grep "\<$_[0]\>" $upgradetmpdir/fullConfiguration.txt`
$_[0]
and$upgradetmpdir/fullConfiguration.txt
contains some matching "text".But
$attrval
is empty after the operation. -
Jonathan Leffler about 14 yearsThat doesn't expand '$variable' which the user requested. It would also require the exact string, with '<' before and '>' after the text.
-
toolic about 14 yearsI think Guaurav needs to show a small sample of his input file, his desired output, and confirm that
$variable
should be expanded by the shell. When more details become available, I'll update my answer. -
Charles Stewart about 14 yearsQuite. In particular, with system commands, you have to worry about which version of the command is installed. Perl is there to make these worries go away.
-
aDev about 14 yearsI think you probably meant to use double quotes there.