将字符串拆分为路径和应用程序

IGG*_*GGt 6 bash debian split

如果我有一个字符串,例如

/home/user/a/directory/myapp.app 
Run Code Online (Sandbox Code Playgroud)

要不就

/home/user/myapp.app 
Run Code Online (Sandbox Code Playgroud)

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"
Run Code Online (Sandbox Code Playgroud)

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

per*_*ror 12

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
Run Code Online (Sandbox Code Playgroud)

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

  • 对不起,我觉得我很幸运。:-) (2认同)

cuo*_*glm 6

使用任何 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
Run Code Online (Sandbox Code Playgroud)

为您节省两个进程分叉。

/myapp.app,myapp.app/path/to/myapp.app, basename/ 的情况下dirname更优雅。另请参阅此问题以进行更多讨论。