string 从路径中提取目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6509650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extract directory from path
提问by Matt
In my script I need the directoryof the file I am working with. For example, the file="stuff/backup/file.zip". I need a way to get the string "stuff/backup/" from the variable $file
.
在我的脚本中,我需要我正在使用的文件的目录。例如,文件= "stuff/backup/file.zip"。我需要一种从变量中获取字符串“ stuff/backup/”的方法$file
。
回答by Matthieu
dirname $file
is what you are looking for
是你要找的
回答by matchew
dirname $file
will output
会输出
stuff/backup
which is the opposite of basename
:
这是相反的basename
:
basename $file
would output
会输出
file.zip
回答by MageParts
Using ${file%/*}
like suggested by Urvin/LuFFy is technically better since you won't rely on an external command. To get the basename in the same way you could do ${file##*/}
. It's unnecessary to use an external command unless you need to.
使用${file%/*}
Urvin/LuFFy 的建议在技术上更好,因为您不会依赖外部命令。要以与您相同的方式获取基本名称${file##*/}
。除非需要,否则没有必要使用外部命令。
file="/stuff/backup/file.zip"
filename=${1##*/} # file.zip
directory=${1%/*} # /stuff/backup
It would also be fully POSIX compliant this way. Hope it helps! :-)
以这种方式它也将完全符合 POSIX。希望能帮助到你!:-)
回答by Urvin Shah
For getting directorypath
from the filepath
:
为了directorypath
从filepath
:
file="stuff/backup/file.zip"
dirPath=${file%/*}/
echo ${dirPath}
回答by Nishchay Sharma
Simply use $ dirname /home/~username/stuff/backup/file.zip
只需使用 $ dirname /home/~username/stuff/backup/file.zip
It will return /home/~username/stuff/backup/
它会回来 /home/~username/stuff/backup/