的bash相当于tcsh的改性剂用于提取路径部件

问题描述 投票:0回答:3

在我的tcsh可以通过以下方式提取路径的末尾第二路径元件

cd /some/long/directory/structure/path/
set x=`pwd`
echo ${x:h:h:t}
directory

我怎么可以这样做在bash?

我的意思是,bash中也有这种改性剂?

bash tcsh
3个回答
1
投票

在非交互式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

3
投票

csh式改性剂可以与历史扩展使用(勿庸置疑的,因为历史扩展从csh借来的)。

$ cd /some/long/directory/structure/path/
$ echo !!:1:h:h:t
echo directory
directory

!!:1选择先前命令的字1(从零计数),所以参数cd

echo directory出现在标准错误,因为壳默认为实际执行该命令产生的前显示历史扩展的结果。)


0
投票
cd /some/long/path/somewhere
x=$PWD
basename "$(dirname "$x")"
>  path

目录名获取参数的父文件夹的绝对路径。基本名称获取参数的名称。

编辑:想起了更好的方法比我以前做的事情。

© www.soinside.com 2019 - 2024. All rights reserved.