拆分字符串以仅获取前5个字符

我想去位置/var/log/src/ap-kernelmodule-10.001-100

但看起来我的代码必须处理ap-kernelmodule-10.002-100,ap-kernelmodule-10.003-101等。我想用拆分字符串到达​​该位置并执行我的命令。 例如:/var/log/src/ap-kernelmodule-10./

这个Linux机器的ruby脚本,所以我使用了Mixlib :: ShellOut。

 begin cmd = Mixlib::ShellOut.new("command run here" , :cwd => '/var/cache/acpchef/src/ap-kernelmodule-10xxx') cmd.run_command end 

你不能同时在多个cwd 。 要为与模式匹配的每个目录运行命令,可以使用Dir#glob

 Dir.glob('/var/cache/acpchef/src/ap-kernelmodule-10*').each do |cwd| Mixlib::ShellOut.new("command run here", cwd: cwd).run_command end 

我不太了解你真正想要实现的目标。 问题很模糊。

你知道你想去/var/log/src/ap-kernelmodule-10.001-100并运行命令,最明显的方法是你可以使用:

 execute "command run here" do cwd "/var/log/src/ap-kernelmodule-10.001-100" end 

但是如果你想为每个目录运行一个命令,就像你在ap-kernelmodule-10.002-100ap-kernelmodule-10.003-101等中ap-kernelmodule-10.003-101使用/var/log/src/ap-kernelmodule-10.*/顺序。

然后你可以做:

 Dir.glob("/var/log/src/ap-kernelmodule-10.*").each do |folder| execute "command run here" do cwd folder end end 

此外,Chef(AFAIK)本身不可能并行执行资源。 因此,可能的解决方法是使用bashruby_block资源来构造要在xargsparallel或类似工具中执行的命令。

希望这可以帮助。