1

我是第一次 Ruby 用户(任何编程代码),我正在尝试在“maid”中创建一个脚本,将我所有的音乐从特定文件夹复制到“自动添加到 itunes”文件夹中:

rule 'Move Downloaded Music to iTunes' do
    FileUtils.cp_r '/Users/*********/Movies/*********/Music/.',
    '/Users/*********/Music/iTunes/iTunes Media/Automatically Add to iTunes/',
    :remove_destination => true
  end

但是,我在同一个文件夹中有非音乐文件,我只想包含音频格式(mp3、m4a 等)的文件

如何附加此代码以便我可以选择要复制的文件类型?

另外,cp_r和cp有什么区别?

任何对我的代码的建议或改进都非常受欢迎 - 我已经看到人们尝试用更复杂的代码做类似的事情,所以从某种意义上说,我担心我的代码太简单了......谢谢你的帮助!

4

3 回答 3

1

您可以使用Dir::glob来查找文件并FileUtils::mv移动它们:

require 'fileutils'

Dir.glob('/Users/.../Music/*.{mp3,m4a}') do |filename|
  FileUtils.mv(filename, '/Users/.../Automatically Add to iTunes/')
end
于 2014-09-23T07:29:59.563 回答
0

要复制特殊类型的文件,请使用

Dir.foreach(absolute_path) do |file|
  if file.downcase.end_with?('.mp3', 'mp4', ....)
      FileUtils.cp(file, final_dir)
  end
end

遍历所有文件夹以选择可以复制的文件,而不是通过您的代码复制所有文件夹。

ps:cp_randcp等于cp -randcp在控制台中,表示复制一个文件夹或者只复制一个文件。

于 2014-09-23T07:07:23.940 回答
0

Maid 提供了一些辅助方法来帮助解决这个问题。让我们将它们单独拼凑起来。

# Find all files in your Downloads
dir('~/Downloads/*')

# Find **any kind of audio files** in your Downloads
where_content_type(dir('~/Downloads/*'), 'audio')

# Copy these specific MP3 files in Downloads to a specific iTunes folder
copy(['~/Downloads/song_1.mp3', '~/Downloads/song_2.mp3'],
     '~/Music/iTunes/iTunes Media/Automatically Add to iTunes/')

# Copy any MP3 files in Downloads to a specific iTunes folder
copy(dir('~/Downloads/*.mp3'),
     '~/Music/iTunes/iTunes Media/Automatically Add to iTunes/')

我们可以将这些部分放在一起以实现完整目的,即将音频文件复制到“自动添加到 iTunes”文件夹中。

Maid.rules do
  rule 'copy audio files to the "Automatically Add to iTunes" folder' do
    copy(where_content_type(dir('~/Downloads/*'), 'audio'),
       '~/Music/iTunes/iTunes Media/Automatically Add to iTunes/')
  end
end

如果您愿意,可以使用变量对其进行分解——毕竟它是 Ruby。

Maid.rules do
  rule 'copy audio files to the "Automatically Add to iTunes" folder' do
    files_in_downloads = dir('~/Downloads/*')
    audio_files_in_downloads = where_content_type(files_in_downloads, 'audio')
    automatically_add_to_itunes_folder = '~/Music/iTunes/iTunes Media/Automatically Add to iTunes/'

    copy(audio_files_in_downloads, automatically_add_to_itunes_folder)
  end
end

我希望这有帮助!

于 2015-01-21T05:13:33.933 回答