将curl重定向到while循环

tay*_*den 3 linux bash curl

有什么方法可以将curl输出重定向到while循环吗?

while read l; do 
  echo 123 $l; 
done < curl 'URL'
Run Code Online (Sandbox Code Playgroud)

还是有更好的方法来做到这一点?我只需要阅读页面的内容,并在每行之前添加一些内容,然后将其保存到文件中即可。

Dav*_*ica 5

您将需要使用进程替换来重定向curl的输出,如下所示:

while read -r l; do 
    echo "123 $l"
done < <(curl 'URL')
Run Code Online (Sandbox Code Playgroud)

您还可以使用带引号的命令替换herestring的输出,如下所示:

while read -r l; do 
    echo "123 $l"
done <<<"$(curl 'URL')"
Run Code Online (Sandbox Code Playgroud)

(尽管最好使用过程替代

注意:要重定向到文件,您可以重定向块的输出,而不是一次重定向一行:

:>outfile    ## truncate outfile if it exists
{
    while read -r l; do 
        echo "123 $l"
    done < <(curl 'URL') 
}>outfile
Run Code Online (Sandbox Code Playgroud)