gkmohit
gkmohit

Reputation: 710

Passing grep as an if condition

Hello I am trying to pass grep as an if condition. That is if grep matches the expression, then I will print the file name and the line number of the file. so far i have this:

for javaFile in `ls -f *.java` ; do
  if  grep -q '^[^/]{2}.*https' $javaFile || grep -q '^[^/]{2}.*http' $javaFile ;
  then
   echo "The file $javaFile has : " >> ~/Desktop/$1_externalServers.txt
   grep -nrE '^[^/]{2}.*http' $javaFile >> ~/Desktop/$1_externalServers.txt     
   grep -nrE '^[^/]{2}.*https' $javaFile >> ~/Desktop/$1_externalServers.txt
   grep -nrE '^[^/]{2}.*ftp' $javaFile  >> ~/Desktop/$1_externalServers.txt
fi
done

But my output file is blank when I do that. Could I know why? :/

Upvotes: 1

Views: 88

Answers (2)

gkmohit
gkmohit

Reputation: 710

This is what I did

  for javaFile in `ls -f *.java` ; do
    if  `cat $javaFile | grep -rqE '^[^/]{2}.*http'` || `cat $javaFile | grep -rqE '^[^/]{2}.*https'` || `cat $javaFile | grep -rqE '^[^/]{2}.*ftp'` ;
    then
echo "The file $javaFile has : " >> ~/Desktop/$1_externalServers.txt
    grep -nrE '^[^/]{2}.*http' $javaFile >> ~/Desktop/$1_externalServers.txt        
    grep -nrE '^[^/]{2}.*https' $javaFile >> ~/Desktop/$1_externalServers.txt
    grep -nrE '^[^/]{2}.*ftp' $javaFile  >> ~/Desktop/$1_externalServers.txt
    fi
    done

The out put is as I expected :)

Upvotes: 0

anubhava
anubhava

Reputation: 786271

grep needs -E option for extended regex and also you shouldn't parse ls's output:

for javaFile in *.java; do
  if  grep -Eq '^[^/]{2}.*https?' "$javaFile" ;
  then
    echo "The file $javaFile has : " >> ~/Desktop/$1_externalServers.txt
    grep -nrE '^[^/]{2}.*http' $javaFile >> ~/Desktop/$1_externalServers.txt     
    grep -nrE '^[^/]{2}.*https' $javaFile >> ~/Desktop/$1_externalServers.txt
    grep -nrE '^[^/]{2}.*ftp' $javaFile  >> ~/Desktop/$1_externalServers.txt
  fi
done

I have also combined your 2 grep commands into one using grep -Eq '^[^/]{2}.*https?' "$javaFile" regex.

Upvotes: 2

Related Questions