0

我有很多 html 文件存在于一个文件夹中。我需要将这些转换为降价,我发现有几个宝石可以一一做到这一点。我的问题是......我如何循环浏览文件夹中的每个文件并运行命令将这些文件转换为单独文件夹上的 md 。

更新

#!/usr/bin/ruby

root = 'C:/Doc'
inDir =  File.join(root, '/input')
outDir =  File.join(root, '/output')
extension = nil
fileName = nil

Dir.foreach(inDir) do |file|
 # Dir.foreach will always show current and parent directories
 if file == '.' or item == '..' then
  next
 end

 # makes sure the current iteration is not a sub directory
 if not File.directory?(file) then
  extension = File.extname(file)
  fileName = File.basename(file, extension)
 end

 # strips off the last string if it contains a period
 if fileName[fileName.length - 1] == "." then
  fileName = fileName[0..-1]
 end

 # this is where I got stuck
 reverse_markdown File.join(inDir, fileName, '.html') > File.join(outDir, fileName, '.md')
4

1 回答 1

2

Dir.glob(directory) {|f| ... }将遍历目录中的所有文件。例如,使用 Redcarpet 库,您可以执行以下操作:

require 'redcarpet'

markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML, :autolink => true)

Dir.glob('*.md') do |in_filename|
  out_filename = File.join(File.dirname(in_filename), "#{File.basename(in_filename,'.*')}.html")
  File.open(in_filename, 'r') do |in_file|
    File.open(out_filename, 'w') do |out_file|
      out_file.write markdown.render(in_file.read)
    end
  end
end
于 2013-05-21T13:54:37.727 回答