【问题标题】:Ruby- How to read all symlinks starting with a patternRuby-如何读取以模式开头的所有符号链接
【发布时间】:2017-11-25 03:50:47
【问题描述】:

在 ruby​​ 中,我如何读取路径上的所有符号链接并将它们放入数组中- 例如,我在路径 /bin- 有以下符号链接-

current_instance1 -> ABC
current_instance2 -> DEF
current_instance3 -> GHI

我想读取所有以“current_”开头的符号链接并将它们填充到一个数组中

【问题讨论】:

标签: arrays ruby symlink


【解决方案1】:

如果您只想列出所有符号链接:

Dir.glob("/path/to/dir/*").find_all { |file| File.symlink?(file) }

如果您想列出符号链接及其目标:

Dir.glob("/path/to/dir/*").map { |file|  {file => File.readlink(file)} if File.symlink?(file) }.compact

【讨论】:

    【解决方案2】:
    Dir.glob("/<path_to_dir>/current_*").map{ |file| File.readlink(file) if File.symlink?(file) }.compact
    

    解释:

    Dir.glob("/<path_to_dir>/current_*") # Matches all files beginning with current_ in the specified path
    
    Dir.glob("/<path_to_dir>/*current_") # Matches all files ending with current_ in the specified path
    
    Dir.glob("/<path_to_dir>/*current_*") # Match all files that have c in them (including at the beginning or end) in the specified path
    
    .map { |file| # iterates and pushes result into array
    
    File.readlink(file) if File.symlink?(file) # Get the target file if the file is a symlink
    
    }.compact # if the file is not a symlink in the specified path, map fills nil by default. Using compact at the end removes all nil entries from the resulting array and gives you only symlink target files in an array.
    

    更新: OP 只想要我们应该使用的文件名File.basename(File.readlink(file))

    【讨论】:

    • 感谢 Vamsi,但它会返回整个路径以及目录名 - ["/ABC" , "/DEF", "/GHI"] 而我只需要 ["ABC", "DEF", "GHI"]。我该怎么做?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多