通过在 Bash 脚本中将 dirname 的结果传送到 basename 来获取父目录名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16855117/
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
Getting parent's directory name by piping the results of dirname to basename in a Bash script
提问by stratis
Given a path like this test/90_2a5/Windows
给定这样的路径test/90_2a5/Windows
I am trying to get the result 90_2a5using the commands dirnameto get the path and after basenameto get the name.
我正在尝试使用命令获取结果90_2a5dirname以获取路径,然后basename获取名称。
The problem occurs when i try to make it in a single line trying to pipe the results from dirnameto basename.
当我尝试在一行中尝试将结果从dirname到basename.
I have tried this but seems that i am using it the wrong way.
我试过这个,但似乎我用错了方法。
path="test/90_2a5/Windows"
finalName= basename var | dirname $path
echo "$finalName"
The problem is that the finalNameis an empty string, meaning that the results from dirnameare not redirecting.
问题是finalName是一个空字符串,这意味着结果dirname没有重定向。
回答by l0b0
You don't pipe them, but rather pass them as parameters:
您不通过管道传输它们,而是将它们作为参数传递:
finalName=$(basename -- "$(dirname -- "$path")")
Some commands quite simply do not accept input streams, but only parameters:
一些命令非常简单地不接受输入流,而只接受参数:
$ echo foo/bar | basename
basename: missing operand
Try `basename --help' for more information.
$ basename foo/bar
bar
回答by Rafael
$ echo 'test/90_2a5/Windows' | xargs dirname | xargs basename
90_2a5
回答by Uwe
Actually, you can also do it without any external program like dirnameor basename, just by using the bash string manipulation operations:
实际上,您也可以在没有任何外部程序(如dirname或 )的情况下执行此basename操作,只需使用 bash 字符串操作操作即可:
path="test/90_2a5/Windows"
# delete from last / to end
dir=${path%/*}
# delete from beginning to last /
finalName=${dir##*/}
echo "$finalName"
回答by suspectus
Use ${path#*/} to strip off the characters up to the first '/'. Then use dirname to remove "/Windows".
使用 ${path#*/} 去掉直到第一个“/”的字符。然后使用 dirname 删除“/Windows”。
finalName=$(dirname ${path#*/})

