Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have an http link :

http://www.test.com/abc/def/efg/file.jar 

and I want to save the last part file.jar to variable, so the output string is "file.jar".

Condition: link can has different length e.g.:

http://www.test.com/abc/def/file.jar.

I tried it that way:

awk -F'/' '{print $7}'

, but problem is the length of URL, so I need a command which can be used for any URL length.

share|improve this question
up vote 5 down vote accepted

Using awk for this would work, but it's kind of deer hunting with a howitzer. If you already have your URL bare, it's pretty simple to do what you want if you put it into a shell variable and use bash's built-in parameter substitution:

$ myurl='http://www.example.com/long/path/to/example/file.ext'
$ echo ${myurl##*/}
file.ext

The way this works is by removing a prefix that greedily matches '*/', which is what the ## operator does:

${haystack##needle} # removes any matching 'needle' from the
                    # beginning of the variable 'haystack'
share|improve this answer
    
Any sort of explanation to go with that? – Questionmark 3 hours ago
    
Sure. Will that do? – DopeGhoti 3 hours ago
    
That is great :) – Questionmark 3 hours ago
    
Thank you !!! That is exactly what I was looking for :) – FunTomas 3 hours ago

With awk, you can use $NF, to get the last field, regardless of number of fields:

awk -F / '{print $NF}'

If you store that string in shell variable, you can use:

a=http://www.test.com/abc/def/efg/file.jar
printf '%s\n' "${a##*/}"
share|improve this answer

basename and dirname work good for URLs too:

> url="http://www.test.com/abc/def/efg/file.jar"
> basename "$url"; basename -s .jar "$url"; dirname "$url"
file.jar
file
http://www.test.com/abc/def/efg
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.