使用curl命令编写Shell脚本循环遍历URLs

29
我一直在尝试编写一个简单的脚本,可以从一个.txt文件中获取查询列表,附加主URL变量,然后爬取内容并将其输出到一个文本文件中。
目前为止,这是我的代码:
#!/bin/bash

url="example.com/?q="
for i in $(cat query.txt); do
    content=$(curl -o $url $i)
    echo $url $i
    echo $content >> output.txt
done

列表:

images
news
stuff
other

错误日志:

curl: (6) Could not resolve host: other; nodename nor servname provided, or not known
example.com/?q= other
如果我直接从命令行使用这个命令,就会将一些输出内容写入到文件中:
curl -L http://example.com/?q=other >> output.txt

最终我希望输出的结果是:

fetched:    http://example.com/?q=other
content:    the output of the page

followed by the next query in the list.
2个回答

37

我猜那应该是非常明显的。:p非常感谢! :) - Mena Ortega
每次迭代,前一个输出都会从output.txt中清除?你知道如何保留它吗? - Arun

5

您有嵌套的引用,请尝试以下方法:

#!/bin/bash

url=https://www.google.fr/?q=
while read query
do
    content=$(curl "{$url}${query}")
    echo $query
    echo $content >> output.txt
done < query.txt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接