How to use input filename to generate output filen

2019-04-13 10:10发布

I've got some input files which I want to encode using Ruby. The output from the encoding should match some pattern based on the filename of the input file. In order to not do this by hand, I want to use Rake as help for automation. Further I'd like to not specify a single task for every input file.

I've tried some FileList "magic" but it didn't work out. Here's the code:

desc 'Create all output from specified input'
task :encode do
  FileList['input/*.txt'].each {|input| file "output/output_#{input}" => input}
end

Anyone can help? I didn't find find anything on the web about multiple output files as dependency.

1条回答
smile是对你的礼貌
2楼-- · 2019-04-13 10:29

I would look into using Rake's rule tasks, which allow tasks to be dynamically defined based on regex rules. See the rakefile rdoc page for details, but here's an example:

# creates the 'output' directory on demand
directory "output"

# define a task rule covering all the output files
rule %r{output/output_} => ['output', proc {|task_name| "input/#{task_name.sub('output/output_', '')}.txt"}] do |t|
  # replace this with your encoding logic
  sh "echo 'file #{t.source}' > #{t.name}"
end

# define a top-level 'encode' task which depends on all the 'output/output_*' tasks
task :encode => Dir['input/*.txt'].map {|x| "output/output_#{File.basename(x).sub('.txt', '')}"}

And then you should be able to run rake encode in a directory with files matching input/*, and have the output files be placed in output/output_*.

查看更多
登录 后发表回答