基于此answer,我试图找到包含指定字符串的所有目录和子目录。现在我有以下代码,它显示所有目录和子目录(字符串模式未实现,这是我想要的):
function fileNames = findAllDirectories(directory, wildcardPattern)
import org.apache.commons.io.filefilter.*;
import org.apache.commons.io.FileUtils;
import java.io.File;
files = FileUtils.listFilesAndDirs( File(directory),...
NotFileFilter(TrueFileFilter.INSTANCE),...
DirectoryFileFilter.DIRECTORY);
fileNames = cellfun(@(f) char(f.getCanonicalPath()),...
cell(files.toArray()),...
'uniformOutput', false);
end
如何指定在目录/子目录名称中搜索名称模式?
例如,如果我有以下目录结构:
C:\aaa
C:\aaa\aaa
C:\aaa\bbb
C:\aaa\ccc
C:\aaa\bbb\ccc
C:\aaa\ddd
C:\aaa\ddd\bbb
我打电话给findAllDirectories('C:\aaa','ccc')
,结果应为:
C:\aaa\ccc
C:\aaa\bbb\ccc
答案 0 :(得分:1)
尝试使用此功能,该功能不使用任何Java库:
function dirPaths = findAllDirectories(baseDirectory, wildcardPattern)
dirPaths = recFindAllDirectories(baseDirectory);
function matchedDirPaths = recFindAllDirectories(searchPath)
files = dir(searchPath); % gets a struct array of the files and dirs in the dir.
files = files(3:end); % removes '.' and '..'
dirs = files([files.isdir]); % filters the results to directories only.
dirNames = {dirs.name}; % takes the names of the directories
matchedNamesIdxs = ~cellfun(@isempty, regexp(dirNames, wildcardPattern)); % applys the pattern search.
matchedDirPaths = fullfile(searchPath, dirNames(matchedNamesIdxs)); % concats to get a full path to the matched directories.
for i = 1:length(dirNames)
currMatchedDirPaths = recFindAllDirectories(fullfile(searchPath, dirNames{i})); % recursively calls the function for the subdirectories.
matchedDirPaths = [matchedDirPaths currMatchedDirPaths]; % adds the output of the recursive call to the current call's output.
end
end
end
使用您的目录结构,同一个调用将输出单元格数组:
' C:\ AAA \ CCC' ' C:\ AAA \ BBB \ CCC'