【问题标题】:Passing grep as an if condition将 grep 作为 if 条件传递
【发布时间】:2014-07-31 07:14:37
【问题描述】:

您好,我正在尝试将 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

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

【问题讨论】:

  • 将for javaFile in `ls -f *.java` 替换为for javaFile in *.java。
  • 没关系,得到我的答案:$

标签: shell if-statement grep


【解决方案1】:

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 -Eq '^[^/]{2}.*https?' "$javaFile" 正则表达式将您的 2 个 grep 命令合并为一个。

【讨论】:

    【解决方案2】:

    这就是我所做的

      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
    

    结果如我所料:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-02
      • 2015-10-06
      • 1970-01-01
      • 2014-12-02
      • 2021-07-07
      • 2017-07-21
      相关资源
      最近更新 更多