如何导航到名称在 Unix 中未知的子目录?

How to navigate into a subdirectory whose name is not known in Unix?

我们有一个典型的目录结构,我们需要导航到一个目录。 问题是目录的名称每次都会更改,我正在尝试通过使用脚本来做到这一点。下面是目录结构

/home/km5001731/cxs/ratc/1670/RATC1670/xxxxx

我想导航到那个 "xxxxx" 目录,但我不知道那个目录的名称,里面还有一些目录,我知道这些目录的名称。

如何导航到我想要的那个?

您可以使用它来查找所有可用的目录

find /home/km5001731/cxs/ratc/1670/RATC1670/ -type d -maxdepth 1

然后,您可以遍历它们以查找有问题的那个

#!/bin/bash
base_path='/home/km5001731/cxs/ratc/1670/RATC1670/'
correct_directory=''
for directory in $(find "$base_path" -type d -maxdepth 1)
do
        subdirectories=$(find "${directory}" -type d -maxdepth 1)
        if grep -q "known_dir1" <<< "$subdirectories" && grep -q "known_dir2" <<< "$subdirectories"
        then
                correct_directory="${directory}"
                break
        fi
done
if [[ "$correct_directory" = "" ]]
then
        echo "Didn't find it!"
        exit
fi
cd "$correct_directory"

或者您可以编写一小段 C 代码递归调用 opendir() 和 readdir(),并使用正则表达式参数来获取独占或包含文件夹名称模式

void examinedir(char *dir, RegExp p)
{
        DIR *dp;
        struct dirent *entry;
        struct stat statbuf;

        if((dp=opendir(dir))== NULL)
        {
                //Error
                return;
        }


        while(entry=readdir(dp))
        {
                char abspath[256] = {0};
                sprintf(abspath, "%s/%s",dir,entry->d_name);
                lstat(abspath, &statbuf);
                if(S_ISDIR(statbuf.st_mode))
                {
                        // It is folder, examine it with p
                        // call examinedir(abspath,p) if you want
                }
                else
                {
                        // file
                }
        }

        closedir(dp);
}

通过下面的操作我们可以导航到当前子目录

!/bin/bash

cd /home/km5001731/cxs/ratc/1670/RATC1670/ Out_dir=ls -Art | tail -n 1 cd /home/km5001731/cxs/ratc/1670/RATC1670/$Out_dir