【问题标题】:How to navigate into a subdirectory whose name is not known in Unix?如何导航到名称在 Unix 中未知的子目录?
【发布时间】:2015-09-24 10:14:23
【问题描述】:

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

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

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

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

【问题讨论】:

  • 如果RATC1670目录下有多个子目录,你怎么知道这次用哪一个?标准是什么?还是 RATC1670 中只有一个目录,但该目录中有多个目录?您的问题在两种情况下模棱两可。 RATC1670 目录下是否还有文件?
  • 我将问题解释为“我知道它不是哪个目录但不知道它是哪个目录”。重读这个问题,我意识到问题更可能是“我不知道文件夹的名称,但我知道里面有什么”。我会改变我的答案。

标签: linux unix directory


【解决方案1】:

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

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"

【讨论】:

    【解决方案2】:

    或者您可以编写一小段 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);
    }
    

    【讨论】:

      【解决方案3】:

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

      !/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

      【讨论】:

        猜你喜欢
        • 2022-01-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-23
        • 2019-10-02
        • 2013-12-31
        • 2016-02-04
        相关资源
        最近更新 更多