sed/awk を使用して URL からホスト名を削除する

sed/awk を使用して URL からホスト名を削除する

さまざまなドメインのURLリストが提供されており、sed、awkなどを使用してホスト名を削除し、パスのみを維持したいと思います。ポートまたはユーザー名@パスワードを含むURLはありません。

入力する:

http://www.example.com/
https://www.example.com/
http://example.com/blog/
https://example.com/blog/
https://www.example.co.uk/blog/
https://example.co.uk/blog/
https://sub.example.co.uk/blog/
https://www.example.com/blog/
https://www.example.com/cases/page/4/
https://www.example.com/cdn-cgi/challenge-platform/h/g/cv/result/7c9123dc38da6841
https://www.example.com/cdn-cgi/challenge-platform/h/g/scripts/jsd/7fe83wdcs/invisible.js
https://www.example.co.uk/cdn-cgi/challenge-platform/h/g/scripts/jsd/7fe83wdcs/invisible.js
https://sub.example.co.uk/cdn-cgi/challenge-platform/h/g/scripts/jsd/7fe83wdcs/invisible.js

出力は次のようになります。

/
/
/blog/
/blog/
/blog/
/blog/
/blog/
/blog/
/cases/page/4/
/cdn-cgi/challenge-platform/h/g/cv/result/7c9123dc38da6841
/cdn-cgi/challenge-platform/h/g/scripts/jsd/7fe83wdcs/invisible.js
/cdn-cgi/challenge-platform/h/g/scripts/jsd/7fe83wdcs/invisible.js
/cdn-cgi/challenge-platform/h/g/scripts/jsd/7fe83wdcs/invisible.js

正規表現のコマンドしか見つけることができないので、誰かが私を助けることができることを願っています。 sedまたはawkコマンドに正しく変換する方法がわかりません。

ベストアンサー1

そしてperl

perl -pe 's|^([^/:]+:)?//[^/]*||' < your-file

代替文字が削除され(およびhttp://host/path両方を処理するために//host/path//、その文字を除くすべての文字が削除されます(たとえば、および/削除されますhost)。user:password@host:8080ftp://user:password@host:8080/pub

これに対応する内容はsed次のとおりです。

LC_ALL=C sed 's|^\([^/:]\{1,\}:\)\{0,1\}//[^/]*||' < your-file

とにかく、s/pattern/replacement/and演算子はsed正規perl表現をパターンとして使用します。基本正規表現のためにsedパール正規表現perl(これは改善され拡張されます。拡張正規表現今日、多くの実装sedでもこのオプションをサポートしています。-E

URIを構造化オブジェクトに解析するURIモジュールもあります。perl

perl -MURI -lpe '$_ = URI->new($_)->path' < your-file

クエリ文字列(のようにhttp://host/path?query)とフラグメント(のように)http://host/file.html#anchorがある場合は、それを削除します。クエリを含めるには(存在する場合)->pathに置き換えます。->path_query

おすすめ記事