是否有一种通用方法来引用沿 cwd 嵌套任意级别深度的路径?这是几乎就像反向相对路径查找一样。
例如:
$ pwd
/Users/somebody/foo/bar/baz
$ echo /[3] <-- 3rd directory from / in current path
/Users/somebody/foo
$ echo ~/[1] <-- 1 directory from ~ in current path
~/foo
答案1
将这些函数放入您的.bashrc
:
parent() {
local count
local arg
count=$(($1+1))
if [ "$2" = "" ]
then
arg="$PWD"
else
arg="$2"
if [[ $arg != /* ]]
then
printf 'Warning: "%s" does not begin with "/".\n' "$arg"
fi
fi
cut -d/ -f1-"$count" <<< "$arg"
}
tparent() { # The ‘t’ stands for “tilde”.
local count
local arg
local home
count=$(($1+1))
if [ "$2" = "" ]
then
arg="$PWD"
else
arg="$2"
fi
if [ "$3" = "" ]
then
home="$HOME"
else
home="$3"
fi
if [[ $home != /* ]]
then
printf 'Warning: "%s" does not begin with "/".\n' "$home"
fi
if [[ $arg/ != $home/* ]]
then
printf 'Error: "%s" does not begin with "%s".\n' "$arg" "$home"
return 1
fi
printf '%s' "~${arg/$home}" | cut -d/ -f1-"$count"
}
它用于 提取第一个cut -d/ -f1-number
N
路径名的组成部分。
number
必须N
+1,因为第一个字段之前的空字符串/
算作第一个字段。
用法:
$ pwd
/home/gman/stack/JW
$ parent 3
/home/gman/stack
$ tparent 1
~/stack
这可以处理带有空格和制表符的路径,但不能处理换行符。