This question is an exact duplicate of:
I have to reach the location /var/log/acpchef/commv123
, where 123
can change to 456
.
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, ...}
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
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.
The begin
keyword in ruby is used to capture errors:
begin
# do something that generates an exception
rescue => exception
# handle the exception
end
A begin
without rescue
, ensure
or else
does nothing.
Also, this is quite similar to a previous question.
来源:https://stackoverflow.com/questions/52887262/how-to-match-a-path-with-the-first-five-characters