首页 > 解决方案 > 如果grep在while循环中不返回任何内容,如何仅显示输出

问题描述

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

所以如果文件是:

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

我的狂欢是:

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 输出的第二个域。我怎样才能做到这一点?

标签: bashloopscurlgrepconditional-statements

解决方案


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

#!/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? 以及如何 grep 变量?.


推荐阅读