Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep in IF statement

Tags:

bash

The following script portion read each line in $next. But when I try to grep particular pattern i.e. "MO" in $next, the error is shown on standard output as:

grep: 40922|OPR: No such file or directory  
grep: MO: No such file or directory  
grep: 12345|OPR: No such file or directory  
grep: MO: No such file or directory   
grep: 12345|12345|202|local|LMNO: No such file or directory  

cat /home/scripts/$E1.out | while read next  
do  
i=`echo $next | awk -F"|" '{print($1)}'`
j=`echo $next | awk -F"|" '{print($2)}'`
k=`echo $next | awk -F"|" '{print($3)}'`
l=`echo $next | awk -F"|" '{print($4)}'`
m=`echo $next | awk -F"|" '{print($5)}'`
n=`echo $next | awk -F"|" '{print($6)}'`
o=`echo $next | awk -F"|" '{print($6)}'`  
if grep -q "MO" $next  
then echo "FOUND;" >> /home/scripts/sql.$E1.out  
else echo "NOT FOUND;" >> /home/scripts/sql.$E1.out  
fi  
done  

$E1.out files looks like :

40922|OPR MO 12345|OPR MO 12345|12345|202|local|LMNO  
like image 541
ErAB Avatar asked Oct 15 '10 15:10

ErAB


2 Answers

The argument you pass in to grep, $next, is being treated as a list of filenames to search through. If you would like to search within that line for a string, say, MO, then you need to either put it in a file and pass that file in as an argument, or pipe it in via standard input.

Here's an example that you can try out on the command line; of course, substitute the variable that you're using for the literal value that I included to illustrate:

if echo "40922|OPR MO 12345|OPR MO 12345|12345|202|local|LMNO" | grep -q "MO"
  then echo "FOUND"
  else echo "NOT FOUND"
fi
like image 77
Brian Campbell Avatar answered Nov 16 '22 07:11

Brian Campbell


if grep -q "MO" ${E1}.out then
  echo "found"
else
  echo "not found"
fi
like image 30
ghostdog74 Avatar answered Nov 16 '22 07:11

ghostdog74