如何将路径与前五个字符匹配 [英] How to match a path with the first five characters
问题描述
我必须到达位置 / var / log / acpchef / commv123
,其中 123
可以更改为 456
。
I have to reach the location /var/log/acpchef/commv123
, where 123
can change to 456
.
我累了 Dir.glob
。我需要 / var / log / acpchef / commv ***
。我的执行将在 mixlibshellout
中。
I tired Dir.glob
. I need /var/log/acpchef/commv***
. My execution will be in mixlibshellout
.
begin
cwd_kernel = Dir.glob('/var/cache/acpchef/commv***')
cmd = Mixlib::ShellOut.new("commandrun", :cwd => cwd_kernel)
cmd.run_command
log 'run'
end
推荐答案
这将使文件名与前五个字符以及之后的任何内容匹配:
This will match a filenename with the first five characters and anything after that:
Dir.glob('/var/cache/acpchef/commv*')
# will match /var/cache/acpchef/commv12345abcdxyz123456
此文件名将与任何三个额外字符相匹配:
This will match a filename with any three extra characters:
Dir.glob('/var/cache/acpchef/commv???')
# will match /var/cache/acpchef/{commv123, commv456, commvabc, ...}
这将匹配具有三个数字的文件名:
This will match a filename with three numbers:
Dir.glob('/var/cache/acpchef/commv[0-9][0-9][0-9]')
# will match /var/cache/acpchef/commv{123, 234, 456, 999, ...}
此外,您的示例未正确使用块语法,并且开始 ..end
而没有 rescue
,这实际上没有任何作用。它应该变成:
Also, your example is not correctly using the block syntax and has begin..end
without rescue
, which does essentially nothing. It should become:
Dir.glob('/var/cache/acpchef/commv???').each do |cwd_kernel|
cmd = Mixlib::ShellOut.new("commandrun", :cwd => cwd_kernel)
cmd.run_command
log 'run'
end
Dir.glob
返回数组,它是结果的集合。 Array.each
返回一个枚举器,基本上是一个对象,它以可用的新值运行具有新值的次数的以下代码块,这意味着您可以使用它为所有结果生成相同的代码块 Dir.glob
。该值通过 | block_argument |
语法传递给块。
Dir.glob
returns an Array, which is a collection of the results. Array.each
returns an Enumerator, which basically is an object that runs the following block of code with a new value as many times as there are new values available, which means you can use it to run the same block of code for all the results of Dir.glob
. The value is passed to the block through the |block_argument|
syntax.
开始
关键字红宝石中的int用于捕获错误:
The begin
keyword in ruby is used to capture errors:
begin
# do something that generates an exception
rescue => exception
# handle the exception
end
A 开始
而没有救援
,确保
或其他
不执行任何操作。
A begin
without rescue
, ensure
or else
does nothing.
此外,这与上一个问题非常相似。
Also, this is quite similar to a previous question.
这篇关于如何将路径与前五个字符匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!