In my bash script I need to extract just the path from the given URL. For example, from the variable containing string:
http://login:password@example.com/one/more/dir/file.exe?a=sth&b=sth
I want to extract to some other variable only the:
/one/more/dir/file.exe
part. Of course login, password, filename and parameters are optional.
Since I am new to sed and awk I ask you for help. Please, advice me how to do it. Thank you!
This perl one-liner works for me on the command line, so could be added to your script.
Note that this assumes there will always be a '?' character at the end of the string you want to extract.
Best bet is to find a language that has a URL parsing library:
or
In bash:
Works only if URL starts with
http://
or a protocol with the same length Otherwise, it's probably easier to use regex withsed
,grep
orcut
...I wrote a function to that will extract any part or the URL. I've only tested it in bash. Usage:
example:
code:
gawk
output
This uses bash and cut as another way of doing this. It's ugly, but it works (at least for the example). Sometimes I like to use what I call cut sieves to whittle down the information that I am actually looking for.
Note: Performance wise, this may be a problem.
Given those caveats:
First let's echo the the line:
Which gives us:
Then let's cut the line at the @ as a convenient way to strip out the http://login:password:
That give us this:
To get rid of the hostname, let's do another cut and use the / as the delimiter while asking cut to give us the second field and everything after (essentially, to the end of the line). It looks like this:
Which, in turn, results in:
And finally, we want to strip off all the parameters from the end. Again, we'll use cut and this time the ? as the delimiter and tell it to give us just the first field. That brings us to the end and looks like this:
And the output is:
Just another way to do it and this approach is one way to whittle away that data you don't need in an interactive way to come up with something you do need.
If I wanted to stuff this into a variable in a script, I'd do something like this:
Hope it helps.