-4

I am aiming to extract host and port number from the url. Could you please update me any examples to do it using perl regex or sed/awk etc?

echo "https://xxxx:port/services" 

I am looking for an oneliner to extract host and port.

brian d foy
  • 129,424
  • 31
  • 207
  • 592
user2586964
  • 35
  • 2
  • 6

2 Answers2

2
perl -MURI -nle'$u = URI->new($_); printf "%s:%s\n", $u->host, $u->port'
  • Works even if the port is implied. (e.g. http://stackoverflow.com/)
  • Works for HTTP, HTTPS, FTP and some others that have the concept of a host and port.

Specifying file to process to Perl one-liner

ikegami
  • 367,544
  • 15
  • 269
  • 518
2

I do this so often that I made a little sprintf-like utility for it: App::url. This isn't useful if you can't install the module and easily use the command-line program, but locally it's quite helpful to extract and rearrange things:

$ url "%h:%p" http://www.example.com/a/b/c
www.example.com:80

$ url "%h:%p" http://www.example.com/a/b/c https://www2.example.org:444
www.example.com:80
www2.example.org:444

$ url "%h -> %I" http://www.example.com/a/b/c
www.example.com -> 93.184.216.34

Often I use this with a little AppleScript I wrote to get all the URLs from all the tabs in Safari:

$ safari-tabs 2>&1 | xargs url %h
www.google.com
github.com
dnschecker.org
securitytrails.com
st.aticpan.org
brian d foy
  • 129,424
  • 31
  • 207
  • 592