将grep作为if条件传递

时间:2014-06-10 13:33:54

标签: shell if-statement grep

您好我试图将grep作为if条件传递。也就是说,如果grep匹配表达式,那么我将打印文件名和文件的行号。到目前为止我有这个:

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

但是当我这样做时,我的输出文件是空白的。我能知道为什么吗? :/

2 个答案:

答案 0 :(得分:2)

grep需要-E选项来扩展正则表达式,而且你不应该解析ls的输出:

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

我还使用grep正则表达式将您的2 grep -Eq '^[^/]{2}.*https?' "$javaFile"个命令合并为一个。

答案 1 :(得分:0)

这就是我做的事情

  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

输出就像我预期的那样:)