【发布时间】:2015-05-16 06:42:33
【问题描述】:
有没有办法将 curl 输出重定向到 while 循环?
while read l; do
echo 123 $l;
done < curl 'URL'
或者有更好的方法吗?我只需要读取页面的内容并在每一行添加一些内容并将其保存到文件中。
【问题讨论】:
有没有办法将 curl 输出重定向到 while 循环?
while read l; do
echo 123 $l;
done < curl 'URL'
或者有更好的方法吗?我只需要读取页面的内容并在每一行添加一些内容并将其保存到文件中。
【问题讨论】:
您将希望使用 进程替换 重定向 curl 的输出,如下所示:
while read -r l; do
echo "123 $l"
done < <(curl 'URL')
您还可以使用带引号的命令替换和herestring的输出,如下所示:
while read -r l; do
echo "123 $l"
done <<<"$(curl 'URL')"
(虽然进程替换是首选)
注意:对于重定向到文件,您可以重定向块的输出,而不是一次重定向一行:
:>outfile ## truncate outfile if it exists
{
while read -r l; do
echo "123 $l"
done < <(curl 'URL')
}>outfile
【讨论】:
你可以使用管道运算符|
curl 'URL' | while read l; do
echo 123 $l >> file.txt
done
【讨论】:
pipe,但就像任何时候你认为cat file | ...一样,你刚刚提交了一个UUOC(不必要使用cat)。 重定向是从一个进程向另一个进程提供输入/输出的正确方法,除非你有两个以上。那么你必须使用管道。其次,每个管道都会生成一个额外的子shell,几乎在所有情况下都不需要。