# Copy files only if pattern found

**URL:** <https://discourse.chef.io/t/copy-files-only-if-pattern-found/13751>\
**Category:** Chef Infra (archive)\
**Created:** [September 26, 2018, 1:33pm UTC](https://discourse.chef.io/t/copy-files-only-if-pattern-found/13751 "2018-09-26T13:33:27Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![israel](https://avatars.discourse-cdn.com/v4/letter/i/b77776/32.png) [@israel](https://discourse.chef.io/u/israel)\
**Post date:** [September 26, 2018, 1:33pm UTC](https://discourse.chef.io/t/copy-files-only-if-pattern-found/13751/1 "2018-09-26T13:33:27Z")

</div>

Hi,

I'm trying to create a recipe that will search pattern in files.  
then it will copy them to /tmp.  
anyone?

My recipe does not work.

execute 'cp\_repo' do  
cwd '/etc/yum.repos.d'  
command 'cp /etc/yum.repos.d/_.repo /tmp'  
only\_if "grep pattern /etc/yum.repos.d/_"  
action :run  
end

---

<div class="post-metadata">

**Author:** ![israel](https://avatars.discourse-cdn.com/v4/letter/i/b77776/32.png) [@israel](https://discourse.chef.io/u/israel)\
**Post date:** [September 30, 2018, 9:14am UTC](https://discourse.chef.io/t/copy-files-only-if-pattern-found/13751/2 "2018-09-30T09:14:24Z")

</div>

Hey Guys,  
Below my recipe that helped me with my question.  
The solution is combine with ruby and chef resource.  
Please tell me what do you think if i need to change something.

require 'open3'  
get\_repo\_files = "grep -l pattern /etc/yum.repos.d/\* | tr '/' ' ' | awk '{print $3}'"

stdout, stdeerr, status = Open3.capture3(get\_repo\_files)

array = stdout.split("\n")  
array.each do | repo|  
execute 'cp pattern file' do  
command "cp /etc/yum.repos.d/#{repo} /tmp/backup/centos7/#{node['hostname']}/yum.repos.d/"  
action :run  
end  
end
