Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

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

If I have a string such as

/home/user/a/directory/myapp.app 

or just

/home/user/myapp.app 

how can I split this so that I just have two variables (the path and the application)

e.g.

path="/home/user/"
appl="myapp.app"

I've seen numerous examples of splitting strings, but how can I get just the last part, and combine all the rest?

share|improve this question
1  
Did you try dirname and basename? – yeti 4 hours ago
up vote 8 down vote accepted

The commands basename and dirname can be used for that, for example:

$ basename /home/user/a/directory/myapp.app 
myapp.app
$ dirname /home/user/a/directory/myapp.app 
/home/user/a/directory

For more information, do not hesitate to do man basename and man dirname.

share|improve this answer
1  
You beat me to it :) LOL. – Rob 4 hours ago
    
27 seconds faster than me. damn :) – nwildner 4 hours ago
2  
Sorry for that, I got luck I think. :-) – perror 4 hours ago
    
cheers quys, I figured it would be something simple that I'd overlooked, but not quite that simple!! – IGGt 4 hours ago
    
Somethimes, you just need to forget about strings, and use the manpages to quick look to what you nee ;) man -k "pathname" should be enough to help you on this. – nwildner 4 hours ago

With any POSIX shell:

$ str=/home/user/a/directory/myapp.app
$ path=${str%/*}
$ app=${str##*/}
$ printf 'path is: %s\n' "$path"
path is: /home/user/a/directory
$ printf 'app is: %s\n' "$app"
app is: myapp.app

save you for two processes forking.

In case of /myapp.app, myapp.app and /path/to/myapp.app, basename/dirname are more graceful. See also this question for more discussion.

share|improve this answer
    
@StéphaneChazelas: Yes, that's why I linked to the question that Gilles pointed it out. Added to the answer. Thanks. – cuonglm 3 hours ago

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.