首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >找不到子目录

找不到子目录
EN

Stack Overflow用户
提问于 2019-06-24 07:10:15
回答 1查看 136关注 0票数 0

我正在尝试在我的脚本中标识某个子目录模式。我得到的问题是目录没有被正确识别。下面是我当前的代码:

代码语言:javascript
复制
parentDir = '/data/home1/fL/user/path/to/subdirectories/'
totalFiles = subdir(fullfile(parentDir, '/*.7'));

name = {totalFiles.name}' % cells containing directories with the .7 ext this is a 118*1 cell
numTotalFiles=length(name); % =118

% this section is supposed to sort through all the subdirectories paths that
% have the pattern A_G/*.7 and p_G/*7 in their pathname but fails to do so. 

for i=1:numTotalFiles
  patternsplit = totalFiles(i).name
  str = ["*/A_G/*.7","*/p_G/*.7"]
  ptrn = ["A_G","p_G"]
  pattern = patternsplit(startsWith(str,ptrn))
  found = pattern
end

我希望输出是包含模式A_G/*.7p_G/*.7的子目录列表。我认为这可能是一个44x1的单元格,其中包含具有这些模式的所有子目录名称。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-24 09:06:52

下面的解决方案使用了另一种方法,而不是前面的方法,它首先列出所有文件名,然后尝试在列表中查找匹配的模式。

这种方法使用递归(在我看来,这个任务需要递归)。主要工作是扫描当前目录的内容以查找.7文件。如果当前目录的名称是A_Gp_G,则返回文件名。然后,它通过子目录调用自己。

请注意,此代码将生成一些用于测试的文件和目录!

代码语言:javascript
复制
% Let's create a directory structure with some files with extension .7

mkdir ('foo/bar/baz/A_G');
mkfile('foo/bar/baz/A_G', 1);
mkdir ('foo/bar/baz/p_G');
mkfile('foo/bar/baz/p_G', 2);

mkdir ('foo/bar/baz/test');
mkfile('foo/bar/baz/test', 99); % should not be found since in directory `test`


mkdir ('foo/bar/p_G');
mkfile('foo/bar/p_G', 3);
mkdir ('foo/bar/A_G');
mkfile('foo/bar/A_G', 4);

mkdir ('foo/p_G');
mkfile('foo/p_G', 5);
mkfile('foo/p_G', 6);


% Here it starts

parent = '.'; % My parent folder is my current folder

l_find_files(parent, false)


function mkfile(d, n)
% just a helper function to generate a file named `<n>.7` in the dirctory <d> 
    fid = fopen(sprintf('%s%s%d.7',d,filesep,n),'w');
    fclose(fid);
end


function res = l_find_files(d, is_candidate)
% recursively scans a directory <d> for *.7 files.
% if is_candidate == true, returns them.
% is_candidate should be set to true if the name of the directory is one of
% {'A_G', 'p_G'}


    files = dir(d);
    res = {};
    if is_candidate
        % get files with extension .7
        % 
        % Instead of using the above `files`, I rescan the directory. Using
        % `files` instead might be faster

        ext7 = dir(fullfile(d,'*.7'));

        res = arrayfun(@(x)fullfile(d, x.name), ext7, 'UniformOutput', false);
    end

    % get the indices of the subdirectories
    issub = [files(:).isdir];
    subdirs = {files(issub).name};

    % call this function for the subdirectories
    for sd = subdirs
        if ~any(strcmp(sd{1}, {'.', '..'})) % omit . and ..
            result = l_find_files(fullfile(d, sd{1}), any(strcmp(sd{1}, {'A_G', 'p_G'})));
            res = [res(:)' result(:)'];
        end
    end

end
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56728336

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档