为什么Ruby中的Dir.glob在带有方括号的文件夹中看不到文件? [英] Why Dir.glob in Ruby doesn't see files in folders named with square brackets?
问题描述
我有这棵树:
.
├── folders
│ ├── foo
│ │ └── fuu.flac
│ ├── foo [bar]
│ │ └── fuu.flac
│ └── foo[bar]
│ └── fuu.flac
└── test.rb
和此代码:
#!/bin/env ruby
## encoding: utf-8
Dir.glob('./folders/*').each do |path|
puts "Contents of #{path} :"
Dir.glob(File.join(path, '*')).each do |file_path|
puts "\t #{file_path}"
end
end
我希望看到我的三个fuu.flac文件.但是,该脚本不会显示名称中带有方括号的文件夹中的文件.
I expect to see my three fuu.flac files. However the script doesn't show the files in the folders with square brackets in the name.
以下是输出:
Contents of ./folders/foo [bar] :
Contents of ./folders/foo[bar] :
Contents of ./folders/foo :
./folders/foo/fuu.flac
这是Ruby的正常行为,还是我想念什么?
Is this a normal beahvior of Ruby, or did I miss something ?
(我正在Ubuntu 12.10下使用Ruby 1.9.3)
(I am using Ruby 1.9.3 under Ubuntu 12.10)
推荐答案
方括号带有特殊含义 在shell globbing 的上下文中. foo [bar]
匹配 foob
, fooa
或 foor
,但显然不匹配 foo [bar]
.如果您确实想动态生成这种模式,则至少需要使用反斜杠转义 \?{} [].
字符:
The square brackets have a special meaning in the context of shell globbing. foo[bar]
matches foob
, fooa
or foor
, but obviously not foo[bar]
. If you really want to dynamically generate such a pattern, you will need to at least escape the characters \?{}[].
using a backslash:
def escape_glob(s)
s.gsub(/[\\\{\}\[\]\*\?]/) { |x| "\\"+x }
end
# ...
Dir.glob("#{escape_glob(path)}/*").each do |file_path|
# ...
end
这篇关于为什么Ruby中的Dir.glob在带有方括号的文件夹中看不到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!