2016-09-20 14 views
2

1つのディレクトリに複数のファイルとサブディレクトリがあります。名前に応じて、これらのファイルを各サブディレクトリに移動する必要があります。例えば:複数のファイルとサブディレクトリがあるディレクトリ:Rubyのファイル名ごとに、これらのファイルを各サブディレクトリに移動する必要があります

ファイル:

Hello.doc 
Hello.txt 
Hello.xls 
This_is_a_test.doc 
This_is_a_test.txt 
This_is_a_test.xls 
Another_file_to_move.ppt 
Another_file_to_move.indd 

サブディレクトリ:

Folder 01 - Hello 
Folder 02 - This_is_a_test 
Folder 03 - Another_file_to_move 

私は必要なものは、フォルダFolder 01 - HelloHelloという3つのファイルを移動することです。ディレクトリFolder 02 - This_is_a_testThis_is_a_testと呼ばれる3つのファイルとFolder 03 - Another_file_to_moveと呼ばれるディレクトリにAnother_file_to_moveという名前の2つのファイルがあります。私は数百ものファイルを持っています。

それが見られるように、フォルダ名は、最後にファイルの名前が含まれていますが、冒頭でFolder + \s + number + \s + -があります。これはグローバルなパターンです。

助けが必要ですか?

+1

あなたは私たちに伝えるために忘れてしまいましたあなたがこれまでに試したことは何ですか? –

+0

私は何度も 'FileUtils'を使ってファイルのコピー、移動、名前の変更などを行ってきました。実際にはRubyにファイル名に焦点を当てる方法を教えています。私は正規表現について考えましたが、およびフォルダ名。 –

答えて

3

急いではなく、段階的に問題を解決してください。私は、次の手順で問題を解決するだろう:拡張子なしで、サブディレクトリからファイルを超える

subdirectories, files = Dir['/path/to/the/directory/*'].partition{|path| File.directory?(path)} 
# TODO ... 

2.反復を

1.個別のファイルを、各ファイルのベース名を取得

subdirectories, files = Dir['/path/to/the/directory/*'].partition{|path| File.directory?(path)} 

files.each do |file| 
    basename = File.basename(file, '.*') 
    # TODO ... 
end 

3.ファイルが移動するサブディレクトリを探します

subdirectories, files = Dir['/path/to/the/directory/*'].partition{|path| File.directory?(path)} 

files.each do |file| 
    basename = File.basename(file, '.*') 
    subdirectory = subdirectories.find {|d| File.basename(d) =~ /^Folder \d+ - #{Regexp.escape(basename)}$/} 
    # TODO ... 
end 

4.移動し、そのディレクトリにファイル完了

require 'fileutils' 

subdirectories, files = Dir['/path/to/the/directory/*'].partition{|path| File.directory?(path)} 

files.each do |file| 
    basename = File.basename(file, '.*') 
    subdirectory = subdirectories.find {|d| File.basename(d) =~ /^Folder \d+ - #{Regexp.escape(basename)}$/} 
    FileUtils.mv(file, subdirectory + '/') 
end 

。しかし、regexpを使ってサブディレクトリを見つけるのは費用がかかり、各ファイルに対してこれをしたくありません。あなたはそれを最適化できますか?

ヒント1:時間のトレードメモリ。
ヒント2:ハッシュ。ここ

+0

優れています。説明をありがとう。私はそれを最適化するための私の試みを行います:) –

0

とは速くなく、クロスプラットフォームソリューション(作業ディレクトリは、ファイルとサブディレクトリを含むディレクトリであると仮定した場合)で、コードが混沌と少しです:

subdirectories = `ls -d ./*/`.lines.each(&:chomp!) 

subdirectories.each do |dir| 
    basename = dir =~ /\bFolder \d+ - (\w+)\/$/ && $1 
    next unless basename 
    `mv ./#{basename}.* #{dir}` 
end 
関連する問題