在我的tcsh可以通过以下方式提取路径的末尾第二路径元件
cd /some/long/directory/structure/path/
set x=`pwd`
echo ${x:h:h:t}
directory
我怎么可以这样做在bash?
我的意思是,bash中也有这种改性剂?
在非交互式bash脚本,历史扩展命令在@ chepner的回答通常不会用。但是,你有参数扩展,如:
$ cd /some/long//directory///structure/path/
$ set x=$(pwd)
$ echo $x
/some/long/directory/structure/path
$ y=${y%/*/*} # each /* is equivalent to one :h
$ y=${y##*/} # equivalent to :t
$ echo $y
directory
该csh
式改性剂可以与历史扩展使用(勿庸置疑的,因为历史扩展从csh
借来的)。
$ cd /some/long/directory/structure/path/
$ echo !!:1:h:h:t
echo directory
directory
!!:1
选择先前命令的字1(从零计数),所以参数cd
。
(echo directory
出现在标准错误,因为壳默认为实际执行该命令产生的前显示历史扩展的结果。)
cd /some/long/path/somewhere
x=$PWD
basename "$(dirname "$x")"
> path
目录名获取参数的父文件夹的绝对路径。基本名称获取参数的名称。
编辑:想起了更好的方法比我以前做的事情。