ErAB
ErAB

Reputation: 915

grep in IF statement

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  

Upvotes: 27

Views: 133172

Answers (3)

Sreesankar
Sreesankar

Reputation: 299

 if tmux ls | grep -q "ABC"; then echo "1";  else echo "2"; fi

Upvotes: -1

ghostdog74
ghostdog74

Reputation: 342333

if grep -q "MO" ${E1}.out then
  echo "found"
else
  echo "not found"
fi

Upvotes: 5

Brian Campbell
Brian Campbell

Reputation: 332776

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

Upvotes: 36

Related Questions