如何从 k shell 中的路径中提取最后的 X 个文件夹

How can I extract the last X folders from the path in k shell

假设我有一个路径名 /server/user/folderA/folderB/folderC,我如何提取(到一个变量)最后几个文件夹?我正在寻找足够灵活的东西来给我 folderC、或 folderB/folderC、或 folderA/folderB/folderC

我正在尝试使用 sed,但我不确定这是最好的方法。

这必须在 ksh 或 csh 中(很遗憾,在我们的机器上没有 bash)

这会让你开始:

arr=( $(echo "/server/user/folderA/folderB/folderC" | sed 's#/# #g') )

echo ${#arr[*]}
echo ${arr[*]}
echo ${arr[3]}
echo "${arr[2]}/${arr[3]}/${arr[4]}"

输出

 5
 server user folderA folderB folderC
 folderB
 folderA/folderB/folderC

IHTH

这可以用 perl 来完成,如果你有的话:

$ path=/server/user/folderA/folderB/folderC
$ X=3
$ echo $path|perl -F/ -ane '{print join "/",@F[(@F-'$X')..(@F-1)]}'
folderA/folderB/folderC

您可以使用数组,但 ksh88(至少是我在 Solaris 8 上测试过的那个)使用 set -A 的旧 Korn Shell 语法,但它不会 (( i++ )),所以这看起来比当代的 ksh93 或 mksh 代码更古怪。另一方面,我也给你一个函数来提取最后 n 项 ;)

p=/server/user/folderA/folderB/folderC
saveIFS=$IFS
IFS=/
set -A fullpath -- $p
echo all: "${fullpath[*]}"
unset fullpath[0] # leading slash
unset fullpath[1]
unset fullpath[2]
echo all but first two: "${fullpath[*]}"
IFS=$saveIFS

# example function to get the last n:
function pathlast {
        typeset saveIFS parr i=0 n

        saveIFS=$IFS
        IFS=/
        set -A parr -- 
        (( n = ${#parr[*]} -  ))
        while (( i < n )); do
                unset parr[i]
                (( i += 1 ))
        done
        echo "${parr[*]}"
        IFS=$saveIFS
}

for lst in 1 2 3; do
        echo all but last $lst: $(pathlast $lst "$p")
done

输出:

tg@stinky:~ $ /bin/ksh x
all: /server/user/folderA/folderB/folderC
all but first two: folderA/folderB/folderC
all but last 1: folderC
all but last 2: folderB/folderC
all but last 3: folderA/folderB/folderC

除第一行设置$p外,函数部分复制即可