展平子文件夹matlab

时间:2016-05-10 18:54:43

标签: matlab directory

我有以下问题:我有一个包含大量文件和子文件夹的文件夹(根文件夹)。每个子文件夹包含许多文件(任何类型)。我想展平所有子文件夹以使根文件夹包含以前存储在子文件夹中的文件。 例如,我有: Main_folder     文件1     文件2     Subfolder1         文件3     Subfolder2         FILE4

我想获得: Main_folder    文件1    文件2    文件3    FILE4

有没有办法在Matlab中自动完成?

1 个答案:

答案 0 :(得分:0)

您可以在MATLAB中轻松地使用dir组合获取目录列表,fullfile构建路径,movefile将文件移动到新位置。

首先在数据的副本上运行以下脚本,以防出现任何问题

function flattenFolder(folder, destination)
    if ~exist('destination', 'var')
        destination = folder;
    end

    %// Get a list of everything in this folder
    D = dir(folder);

    %// Grab just the directories and remove '.' and '..'
    folders = {D([D.isdir]).name};
    folders = folders(~ismember(folders, {'.', '..'}));

    %// Get all the files
    files = {D(~[D.isdir]).name};

    %// Remove .DS_store files
    files = files(~strcmpi(files, '.DS_store'));

    %// For every subfolder, call this function recursively
    for k = 1:numel(folders)
        flattenFolder(fullfile(folder, folders{k}), destination);
    end

    %// If the source and destination are the same, don't worry about moving the files
    if strcmp(folder, destination)
        return
    end

    %// Move all of the files to the destination directory
    for k = 1:numel(files)

        destfile = fullfile(destination, files{k});

        %// Append '_duplicate' to the filename until the file doesn't exist
        while exist(destfile, 'file')
            [~, fname, ext] = fileparts(destfile);  
            destfile = fullfile(destination, sprintf('%s_duplicate%s', fname, ext));
        end

        movefile(fullfile(folder, files{k}), destfile);
    end 
end

然后用你的例子你将其称为:

flattenFolder('Main_Folder')

注意

正如其他人所说,MATLAB不是完成这项任务的理想工具。由于您使用的是OS X,因此从命令行使用bash可能是更好的选择。

find Main_Folder/ -mindepth 2 -type f -exec mv -i '{}' Main_Folder/ ';'