如何grep curl -I头信息

Min*_*int 5 linux redirect curl

我正在尝试从网站获取重定向链接,curl -I然后grep使用"位置"然后sed输出位置文本,以便我留下URL.

但这不起作用.它将URL输出到屏幕,而不是把它

test=$(curl -I "http://www.redirectURL.com/" 2> /dev/null | grep "location" | sed -E 's/location:[ ]+//g')
echo "1..$test..2"
Run Code Online (Sandbox Code Playgroud)

然后输出:

..2http://www.newURLfromRedirect.com/bla
Run Code Online (Sandbox Code Playgroud)

这是怎么回事?

Joh*_*web 6

正如@ user353852指出的那样,你在输出中有一个回车符,curl只有当你尝试使用echo它之后的任何字符时才会显现.该less传呼机显示这件事作为^M

您可以使用sed删除"控制字符",如下例所示:

% test=$(curl -I "http://www.redirectURL.com/" 2>|/dev/null | awk '/^Location:/ { print $2 }' | sed -e 's/[[:cntrl:]]//') && echo "1..${test}..2"
1..http://www.redirecturl.com..2
Run Code Online (Sandbox Code Playgroud)

备注:

我使用awk而不是你的grep [...] | sed方法,节省了一个过程.

对我来说,curl返回以'Location:'开头的行中的位置(大写'L'),如果您的版本实际上是用小写'l'报告它,那么您可能需要相应地更改正则表达式.