简体   繁体   中英

Check if some files in array exist in directory

I wrote the following code to rename some files in a directory (from 'rb' to 'origin' ):

original_files = ['test1.rb', 'test2.rb']

ruby_block "Rename file" do
  block do
    for filename in original_files
      newname = filename.split(".")[0] + '.origin'
      ::File.rename("C:\\Test\\#{filename}", "C:\\Test\\#{newname}")
    end
  end
end

When I run it for the second time, I get an error that these files don't exist, which is expected.

How can I check if these files exist or not like this:

if ::File.exist?("C:\\Test\\*.origin")
  Chef::Log.info("########## Your files are already renamed ############")
else
  my_code
end

or in another way (maybe to check it in loop)?

This is my solution after numerous attempts:

origin_files = ['test1.rb', 'test2.rb']
dir_path = "C:\\Test"

ruby_block "Rename file" do
    block do 
        for filename in origin_files
            newname = filename.split(".")[0] + '.origin'
            if ::File.exist?("#{dir_path}\\#{newname}")
                Chef::Log.info("### Your file: #{newname} already renamed ###")
            else
                ::File.rename("#{dir_path}\\#{filename}", "#{dir_path}\\#{newname}")
            end
        end     
    end             
end

you can check this files like this code

files = ["test1.rb", "test2.rb"]

path = "C:/test"

files.each { |file_name|
  base_name = File.basename(file_name, ".rb")
  new_name = base_name + ".origin"
  if File.exists?(File.join(path, new_name))
    Chef::Log.info("########## Your file #{base_name} are already renamed ############")
  elsif File.exists?(File.join(path, file_name))
    File.rename(File.join(path, file_name), File.join(path, new_name))
    Chef::Log.info("########## Your file #{base_name} was renamed ############")
  else
    Chef::Log.info("########## Your file #{file_name} not exist ############")
  end
}

You can use Chef guard for this purpose. It automatically logs the event during the chef-client run as

ruby_block xxx (skipped due to not_if)

Here is the example:

origin_files = ['test1.rb', 'test2.rb']
dir_path = "C:\\Test"

origin_files.each do | old_file |
    base_name = File.basename(old_file, ".rb")
    newfile = base_name + ".origin"
    ruby_block "rename #{old_file}" do
      block do
        File.rename(File.join(dir_path, old_file), File.join(dir_path, newfile))
      end
      not_if { File.exist?("#{dir_path}\\#{newfile}") }
    end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM