bash - 如果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 输出的第二个域。我怎样才能做到这一点?
解决方案
即使有可能提供单线,我也喜欢用一个更有条理的例子来展示如何实现目标。
#!/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 变量?.
推荐阅读
- pandas - 按关键字列表过滤行
- python - LSTM 层上的时间注意力?
- javascript - 更新猫鼬记录内的数组内的值
- c# - 随机化索引而不重复
- puppet - 如何在 sles11 上安装 puppet-agnet 7?
- javascript - Javascript操作对象结构
- spring-rest - 当请求中提供未定义的参数时,使用 Java 对象映射查询参数不会引发错误
- visual-studio-code - 如何使 vs code 将我的 c 程序的输出放在 TERMINAL 面板中?
- android - 在应用程序中隐藏一个 txt 文件而不显示它
- python - 如何让 Alembic 在 TEXT 列上发出长度约束?