找不到子目录

时间:2019-06-23 23:10:14

标签: matlab directory pattern-matching filepath subdirectory

我正在尝试在脚本中标识某个子目录模式。我遇到的问题是目录标识不正确。 这是我当前的代码:

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的单元格,其中包含具有这些模式的所有子目录名称。

1 个答案:

答案 0 :(得分:2)

以下解决方案使用的方法不同于您以前的解决方案,该方法首先列出所有文件名,然后尝试在列表中查找匹配的模式。

此方法使用递归(我认为此任务要求递归)。完成了一项主要工作,该功能可扫描当前目录中的.7文件。如果当前目录的名称为A_Gp_G,则返回文件名。然后,它使用子目录进行调用。

请注意,此代码会生成一些文件和目录进行测试!

% 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