有没有办法根据最后一个字符 cd 进入目录?

her*_*ity 8 bash cd-command

我有以 开头的目录,164但它们根据最后几位数字而有所不同。如果不是最后一位数字本身,我想根据最后几位数字 cd 进入一个目录,比如9vs 8。目录的最后一位数字是唯一的。有可能这样做吗?当我从第一个数字开始时,自动完成列出了许多可能性164

Ste*_*itt 33

使用 Bash,是的,您可以使用通配符:

cd /path/to/*9/
Run Code Online (Sandbox Code Playgroud)

(替换9为您需要的任意数量的数字;/path/to/如果您位于包含所有164...目录的目录中,则可以删除)。

您需要确保表达式足够具体以解析为单个目录,否则cd将更改为其参数中指定的第一个目录(在 4.4 版之前的 Bash 中),或失败并出现错误(Bash 4.4 及更高版本使用 构建CD_COMPLAINS)。(注意 Zsh 或 Ksh,它们具有两个参数形式cd,您可能会意外调用它们,尽管仅当您当前的路径包含第一个参数时。)

你也可以在输入上面的命令后,在执行它之前完成选项卡;如果有多个目录匹配,您的 shell 将列出所有目录。


Tho*_*key 18

如果它们除了最后几位数字之外实际上是不同的,则可以在 cd 命令中使用通配符,例如,

cd 164*8
Run Code Online (Sandbox Code Playgroud)

(如果它们实际上并不不同,shell 会通过生成错误消息来提醒您这一点)。


gle*_*man 6

你可以做一些自定义的事情。

mycd() {
    local ng=$( shopt -p nullglob )
    shopt -s nullglob
    local status

    local matches=( *"$1"/ )  # directories ending in the parameter
    case ${#matches[@]} in
        0) echo "no directory ends with $1" >&2; status=1 ;;
        1) cd "${matches[0]}"; status=$? ;;
        *) echo "multiple directories end with $1" >&2; status=1 ;;
    esac

    $ng   # restore the previous nullglob setting. specifically unquoted
    return $status
}

mycd 89  # cd to the subdir ending with 89
Run Code Online (Sandbox Code Playgroud)

这可以扩展为使用 select 语句,当有多个匹配的目录时,允许您选择想要的目录。