如何为以下情况编写单行 cd 命令?

How do I write a one-liner cd command for the following case?

我有 2 个目录
testing_dir
testing_dir_win

所以我需要 cd 到 testing_dir。但情况是这样

目录可以是
testing_dir 或 testing_dir-2.1.0
testing_dir_win 或 testing_dir_win-1.3.0

我的脚本应该只采用 testing_dir 或 testing_dir-2.1.0(基于哪个可用)

我写的很长:

str=`ls folder_name|grep ^testing_dir`
arr=(${str//" "/ })
ret=""
for i in "${arr[@]}"
do
    if [[ $i != *"testing_dir_win"* ]] ; then
            ret=$i
    fi
done

但是这个问题有单线的吗?类似于 cd testing_dir[\-]?(顺便说一句,这不起作用)。

使用带有 grep 过滤器的命令:

cd `ls | grep -w testing_dir`

此命令将匹配 testing_dir 目录,无需担心版本。

P.S 如果有很多版本,它将进入最早的版本,因此根据您的用例添加“head -1, tail -1”

如果您的脚本包含

shopt -s extglob

您可以使用:

cd testing_dir?(-[[:digit:]]*) || exit

...如果您保证只存在一个匹配项。

没有那个保证,可以直接设置

arr=( testing_dir?(-[[:digit:]]*) )
cd "${arr[0]}" || exit