2

多くの短い URL を含む txt ドキュメントがあります。各 URL は 1 行で区切られています。最終的なリンクを取得するために URL を解決したいです。また、一部の URL は 2 回リダイレクトされます。出力形式で最終的な URL を取得するためにこれを自動化する方法1行に1つの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 に答える