2013-05-21 1 views
0

나는 하나의 폴더에있는 많은 HTML 파일을 가지고 있습니다. 나는 이것들을 마크 다운으로 변환 할 필요가있다. 나는 하나씩이 위대한 일을하는 몇 가지 보석을 발견했다. 내 질문은 ... 폴더의 각 파일을 반복하고 이들을 별도의 폴더에있는 md로 변환하는 명령을 실행하는 방법은 무엇입니까? 디렉토리 내의 모든 파일을 통해배치 변환 HTML을 마크 다운

UPDATE

#!/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

이것은 반복과 반복에 관한 질문입니다. Ruby가'Dir'과'File' 클래스에서 빌드 한 것을 보셨습니까? 가장 좋은 대답은 파일 구성 방법과 보석의 한계 (이름을 적어주십시오)입니다. 귀하의 질문에 첫 번째 시도를 함께 넣어, 우리는 좋은거야! –

답변

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 
관련 문제