bash Unix 命令获取没有基本名称的文件路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23103042/
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
Unix Command to get file path without basename
提问by logan
I have following file in unix directory
我在unix目录中有以下文件
/home/files/myfiles/good.txt
I need to extract the file path alone
我需要单独提取文件路径
Expected output: /home/files/myfiles
预期输出:/home/files/myfiles
Note: I can not use cut operations as the file path is dynamic. I am getting the filename and filepath as single user input to the shell script
注意:我不能使用剪切操作,因为文件路径是动态的。我将文件名和文件路径作为单个用户输入到 shell 脚本中
回答by mathk
Try
尝试
$ dirname /home/files/myfiles/good.txt
回答by Roberto Reale
Should do the job:
应该做的工作:
echo /home/files/myfiles/good.txt | sed s,/*[^/]*$,,
回答by jasonwryan
Without spawning another process, you can use parameter expansion:
在不产生另一个进程的情况下,您可以使用参数扩展:
file=/home/files/myfiles/good.txt
echo "${file%/*}"
/home/files/myfiles
回答by Fredrik Pihl
FWIW, cut
CAN do it dynamically with a little help of rev
FWIW,cut
可以在一些帮助下动态地做到这一点rev
$ echo "/home/files/myfiles/good.txt" | rev | cut -d/ -f2- | rev
/home/files/myfiles
$ echo "/home/files/myfiles/yourfiles/good.txt" | rev | cut -d/ -f2- | rev
/home/files/myfiles/yourfiles