Reputation: 2507
I have the following directory and it has the following files:
/tmp/test/file1.txt
/tmp/test/file1.txt.backup
/tmp/test/mywords.csv
How do I use the file
module to just remove file1*
files?
Upvotes: 17
Views: 35132
Reputation: 3137
edit: Ansible 2.0 has been released now, so the previous answer should work, and you can also now loop over fileglobs. Note this only works if you are running Ansible locally:
- file:
path: "{{item}}"
state: absent
with_fileglob:
- /tmp/test/file*
original answer:
I can't find a way to do this currently without dropping to the shell, however if you can drop to the shell to gather a list of files that match the pattern and save that as a variable, then you can loop over the file module with with_items
Ansible 2.0 will include a "find" module that would get the list for you: http://docs.ansible.com/ansible/find_module.html
Here's a couple of tasks that should do it in ansible 2.0, but I don't have it installed so I haven't tested it and may be accessing the results of the find module incorrectly.
- find:
paths: "/tmp/test"
patterns: "file*"
register: result
- file:
path: "{{item.path}}" #correction code
state: absent
with_items: " {{ result.files }}"
Upvotes: 30
Reputation: 459
- hosts: srv-lnx
gather_facts: no
tasks:
- shell: "find /var/tmp/collect -maxdepth 1 -type f | awk -F/ '{print $NF}'"
register: result
- debug: var=result
- fetch: src=/var/tmp/collect/{{ item }} dest=/appl/collect/data flat=yes
with_items: result.stdout_lines
Upvotes: 0
Reputation: 5900
you can use the find + file module as shown above, but on ansible < 2.0 I got this error:
ERROR: find is not a legal parameter in an Ansible task or handler
the following command will do (you may replace the -regex with -name "files1*"):
- name: delete files
shell: 'find /tmp/test/ -maxdepth 1 -type f -regex "/tmp/test/file1.*" -exec rm -rf {} \;'
Upvotes: 1
Reputation: 1371
So I'm not in front of a linux terminal but you can use this if you are trying to ensure you only remove things that are files. Should work but you might need to tweak it.
find . -name files1* -type f -exec basename {} \; | xargs rm
Upvotes: 0