厨师食谱:过滤要删除的文件列表

问题描述 投票:0回答:1

我有一个变量来存储应保留的文件

default['keep']['files'] = ['a.txt', 'b.txt']

并且下面的文件存在于服务器上

'a.txt', 'b.txt', 'c.txt', 'd.txt'

我要删除默认情况下不存在的那些文件['keep'] ['files'],即c.txt和d.txt但我不知道如何获取要删除的文件列表。

// How should I get the list so that i can loop it?
???.each do |file_name|
  directory "Delete #{file_name}" do
    path my_folder_path
    recursive true
    action :delete
  end
end
ruby chef
1个回答
0
投票

您可以从文件列表数组中减去keep数组,这将为您留下要删除的文件名数组。例如

a1 = ['file1', 'file2']
a2 = ['file1', 'file2', 'file3', 'file4']
a3 = a2 - a1 #results in a3 => ['file3', 'file4']

所以您可以做类似的事情

files_to_keep = ['a.txt', 'b.txt']
all_files = Dir.entries
files_to_delete = all_files - files_to_keep
files_to_delete.each do |file_name|
  if ! Dir.exist? #Check that the file name is not an actual directory
    # write your code to delete the file named file_name
  end
end

但是您可能想先对数组排序,代码未经测试,但应该没问题

© www.soinside.com 2019 - 2024. All rights reserved.