2

我有一个包含许多短 url 的 txt 文档。每个 url 由一行分隔。我想解析 URL 以获得最终链接。还有一些 URL 被重定向两次。如何自动执行此操作以获取具有输出格式的最终​​ url每行一个网址?更新:输入文本文件:

http://www.example.com/go/post-page-1 
http://www.example.com/go/post-page-2 
http://www.example.com/go/post-page-3 

txt文件中需要的输出格式:

http://www.example.org/post-page-name
http://www.example.org/post-page-name
http://www.example.org/post-page-name

以下是链接的重定向方式:

Initial URL:http://www.example.com/go/post-page 
    ==>301 Permanent Redirect

Intermediate url:http://click.affiliate.com/tracking?url=http://www.example.org/post-page-name
==>302 Temporary Redirect

Final URL: http://www.example.org/post-page-name

这是我尝试过的代码,但它没有将 URL 解析为最终链接,而是解析为中间链接。

#!/bin/bash
rm resolved_urls.txt
for url in $(cat url.txt); do
        wget -S "$url" 2>&1 | grep ^Location >> resolved_urls.txt
done
4

2 回答 2

1

因此,您的要求并不是 100% 清楚。但是我所看到的以及我所猜测的,我认为这会为您做到:

#! /bin/bash
# Use the urls.txt as your input file for wget
# Use the url-redirect.txt as your output file from wget.

wget -S -i urls.txt -o url-redirect.txt

# Grep for your "Final URL" output, extract the URL, assuming
#   the output you provided is what you're looking for, and is 
#   uniform, and redirect to your resolved_urls.txt file.

grep 'Final URL' url-redirect.txt | cut -d ' ' -f3>resolved_urls.txt

# Remove your trash temp file.
rm url-redirect.txt

如果没有所有重定向,这可能会快很多,但我认为这可以满足您的需求。

于 2014-08-25T18:02:15.060 回答
0

尝试这样的事情:

#!/bin/bash

function getFinalRedirect {
    local url=$1
    while true; do
        nextloc=$( curl -s -I $url | grep ^Location: )
        if [ -n "$nextloc" ]; then
            url=${nextloc##Location: }
        else
            break
        fi
    done

    echo $url
}

url="http://stackoverflow.com/q/25485374/1563512"
getFinalRedirect $url

谨防无限重定向。这会产生:

$ ./test.bash 
http://stackoverflow.com/questions/25485374/how-to-resolve-url-redirects

然后,调用文件上的函数:

while read url; do
    getFinalRedirect $url
done < urls.txt > finalurls.txt
于 2014-08-25T18:07:37.317 回答