remove all files containing a certain name within a directory

百般思念 提交于 2019-11-29 09:18:56

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

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 {} \;'

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
Diego Roberto Dos Santos
- 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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!