Scripting Question - Strip filename from URL leaving Domain and Path
I'm new to linux and scipting in general. I have a text file with several thousand URL's - 1 URL per line. I need to come up with a few simple commands that can parse the domain information and path from a URL while stripping the filename and extension.
For example, if I have http://blah.com/123/abc.exe I want to strip the abc.exe and just leave http://blah.com/123/ Can anyone please help me out with this? Thanks |
Now personally I'd do this in python, because it is easier to follow in this example without having to learn about regular expressions (http://en.wikipedia.org/wiki/Regular_expressions).
You should also have python installed. Code:
#!/usr/bin/env python Then we use split() on each url; which as it suggests splits further by the forward slash into another array (We're defining it on the fly, no need to name it) and then steps into every element in there, adds it to the string 'url_tmp' and adds a forward slash back in. There are better ways, but this is a small and powerful and will be more than good enough |
That could work too. I'm just trying to learn the basics without getting too complex. :-)
Here is what I ended up using that worked well: rev urllist | cut -d/ -f2- | rev > newurllist |
Another perspective: Learn Regular Expressions
In your example, you have more than the domain name---that would be "http://blah.com" Here are 2 example Regexes that match common URLs (Not tested--may need extended regex flags. Note also that the "/" needs to be escaped in some situations): ##In a way, this might be more robust, but it also matches all manner of invalid URLs. In your case, you might want to match everything that was intended to be a URL in the context.) Using the second example, you can do the editing with SED: Code:
sed 's%\(http://[^/]*\)[^ ]*%\1%g' filename > newfilename Again---none of this tested. For a good reference on SED an other things, go here: http://www.grymoire.com/Unix/ |
Hmmm---perhaps OP has a better answer---and in less time. Funny how that happens.....;)
|
Code:
while read |
My suggestion would have been along the lines of--
Code:
for i in $(cat filename.txt); do echo $i | cut -f1-$(echo $i | awk -F\/ '{print NF-1}') -d\/; done I don't often use rev and often lament that cut doesn't support working backwards on a line... /facepalm. Good solution OP |
Quote:
|
Code:
#!/bin/bash |
Alternatively
Code:
basename http://blah.com/123/abc.exe Code:
dirname http://blah.com/123/abc.exe |
Lots of interesting and good answers in this thread. Make sure you tag your posts up to make them easier for others to find in the future!
|
All times are GMT -5. The time now is 02:25 PM. |