【问题标题】:How to automatically find files of a specified type in the current directory or any specified sub-folders in Ruby?ruby - 如何在当前目录或Ruby中的任何指定子文件夹中自动查找指定类型的文件?
【发布时间】:2011-04-14 23:20:04
【问题描述】:

我正在使用以下代码将文件从 php 转换为 html。为了让它工作,我必须在第二行输入每个文件的名称。

p "convert files"
%w(file1 file2 file3).each do |name|
  system %(php #{DIR}/#{name}.php > #{DIR2}/#{name}.htm)
end

谁能告诉我如何制作它,它会自动在主目录中查找任何 .php 文件,并在任何已定义的文件夹及其子文件夹中查找其他 .php 并将它们保存在类似的文件夹名称中?

例如:

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

【问题讨论】:

    标签: ruby automation build-automation rake rakefile


    【解决方案1】:

    最简单的方法是使用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
    

    Dir.glob (AKA Dir[]) 的 ** 模式递归匹配目录,因此 Dir[**/*.php] 将为您提供当前目录下的所有 PHP 文件。

    【讨论】:

    • 谢谢!因此,如果我想排除像“includes”这样的目录(可能还有其他目录),我该怎么做呢?
    • @Cofey:最简单的方法是在块内添加if(i_like_this_path(File.dirname(php)) 检查。 File.dirname 会给你文件名的目录部分,你必须为i_like_this_path() 提供一些合理的东西。
    • @Andrew Grimm:请不要理会我的缩进。我发现两个空间的 Ruby 标准完全不可读,我对它的态度与 Ruby 社区一样多:)
    • @mu 太短了,我终于开始尝试您的脚本,它似乎没有进入子文件夹来搜索 .php 文件。它只是在主目录中创建 .htm 文件。有什么想法吗?
    • @Cofey: 是没有找到所有的 PHP 文件还是搞砸了htm 路径? Dir['**/*.php'] 应该可以找到当前目录下的所有 PHP 文件。当你在irb 的正确目录中时,Dir['**/*.php'].inspect 必须说什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 2013-03-30
    • 2013-01-04
    • 2016-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多