【问题标题】:How to only show output if grep returns nothing in while loop如果grep在while循环中不返回任何内容,如何仅显示输出
【发布时间】:2020-08-05 17:22:14
【问题描述】:

我有一个包含域列表的文件。我正在遍历此列表以使用 curl 和 grep 特定元素。它按预期进行,但是,我需要 相反的;意思是,我只需要在 没有 找到我的搜索字符串时查看输出。

所以如果文件是:

https://www.somewebsite1 dot com
https://www.somewebsite2 dot com
https://www.somewebsite3 dot com

我的 bash 是:

while read n;
do
echo $n;
curl -s $n | grep 'class="my_class"';
done < /my/file/location.txt

输出是:

https://www.somewebsite1 dot com
                    <p class="my_class">"some_value"</p>
https://www.somewebsite2 dot com <--- NEED ONLY THESE LINES
https://www.somewebsite3 dot com
                    <p class="my_class">"some_value"</p>

我只想要没有任何 grep 输出的第二个域。我怎样才能做到这一点?

【问题讨论】:

    标签: bash loops curl grep conditional-statements


    【解决方案1】:

    即使有可能提供单线,我也喜欢用一个更有条理的例子来展示如何实现目标。

    #!/bin/bash
    
    SEARCHPATTERN=$1
    
    while read URL; # from list of URLs
    do
    
      # echo "Going to gather CONTENT of ${URL}"
      CONTENT=$(curl --silent https://${URL} --write-out " %{http_code}")
      # echo "Gathered CONTENT is\n\n${CONTENT}"
    
      # Check if provided search pattern is part of the content
      if grep -q ${SEARCHPATTERN} <<< ${CONTENT}; then
        echo "Found ${SEARCHPATTERN} in ${URL}"
      else
        echo "Did NOT found ${SEARCHPATTERN} in ${URL}"
      fi
    
    done < URLs.lst
    

    您还可以利用Can grep return true/false?How to grep on a variable?

    【讨论】:

      猜你喜欢
      • 2011-05-25
      • 2016-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多