开发者

How to automatically find files of a specified type in the current directory or any specified sub-folders in Ruby?

开发者 https://www.devze.com 2023-02-25 11:14 出处:网络
I am using the following code to convert files from php to html. In order for it to work, I have to enter the name of each file on the second line.

I am using the following code to convert files from php to html. In order for it to work, I have to enter the name of each file on the second line.

p "convert f开发者_高级运维iles"
%w(file1 file2 file3).each do |name|
  system %(php #{DIR}/#{name}.php > #{DIR2}/#{name}.htm)
end

Can someone tell me how to make it so it will automatically find any .php files in the main directory and look in any defined folder and their sub-folders for additional .php and save them in similar folder names?

For example:

file1.php -> file1.htm
about-us/file2.php -> about-us/file2.htm
contact-us/department/file3.php -> contact-us/department/file3.htm


The easiest way is to use Dir:

Dir.chdir('where_the_php_files_area')
Dir['**/*.php'].each do |php|
    htm = 'where_the_html_files_should_go/' +  php.sub(/\.php$/, '.htm')
    system("php #{php} > #{htm}")
end

The ** pattern for Dir.glob (AKA Dir[]) matches directories recursively so Dir[**/*.php] will give you all the PHP files under the current directory.

0

精彩评论

暂无评论...
验证码 换一张
取 消