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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 10:13:01  来源:igfitidea点击:

Unix Command to get file path without basename

linuxbashshellunix

提问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, cutCAN 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