2016-05-10 5 views
-1

私には次の問題があります。多くのファイルとサブフォルダを含むフォルダ(ルートフォルダ)があります。各サブフォルダには、(任意のタイプの)多数のファイルが含まれています。私はすべてのサブフォルダを平らにして、以前にサブフォルダに保存されていたファイルを含むルートフォルダを作成したいと考えています。たとえば は私が持っている: Main_folder はFile1 File2の Subfolder1 FILE3 Subfolder2 FILE4サブフォルダの展開matlab

私が取得したい: Main_folder はFile1 File2の FILE3 FILE4

があることを行うための方法がありますMatlabでは自動的に?

+2

環境について教えてください。 Windows?マック? Linux? Mac/Linuxの場合、私はbashシェルスクリプトを使ってこれを行います。これは実際にMatlabのためのものではありません... –

+0

文字通り、さまざまなツールでこれを行う方法は何千もあります... – Matt

+0

大丈夫ですか?あなたはそれを行うためのMATLABの方法を知っていますか? – David

答えて

0

あなたは簡単に自分の新しい場所にファイルを移動するmovefile、パスを構築するために、ディレクトリのリストを取得するためにdirの組み合わせを使用して、MATLABでfullfileこれを行うことができます。

まず、それは次にあなたの例で、あなたがこれを呼ぶだろうすべての問題

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') 

注釈

他のhavつまり、MATLABはこの作業には理想的なツールではありません。あなたはOS X上にいるので、コマンドラインからbashを使うほうが良い選択かもしれません。

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

ありがとう、ありがとう、本当に素晴らしい解決策であり、それは完全に動作します。ちょっと別のこと:あなたはこの制御をどうやって行うのか考えていますか?Main_Folderで各ファイルを動かしているときに、同じ名前のファイルを見つけたら、移動しているファイルの名前を変更してください。システムが動いているファイルの?ありがとうございました – David

+0

@David既に '_duplicate'を目的地にあるファイルに追加するように変更しました。 – Suever

+0

あなたが行った変更でコードを実行しようとしましたが、次のエラーが表示されます(私は隠しファイル.DS_Storeを持っています)。 – David

関連する問題