lubik
lubik

Reputation: 79

Ansible delete files recursively with regex

I have a structure:

From the dir1, I want to delete recursively all the files that matches regular expression: .*?_(?!2)[0-9]{2,}\.(dat|DAT) (anything at the beginning, not followed by 2, followed by at least 2 digits and ended by .dat/.DAT). The files that should match and be deleted are bold.

I tried:

- name: delete files
  shell: 'ls -R | grep -P ".*?_(?!2)[0-9]{2,}\.(dat|DAT)" | xargs -d"\n" rm'
  args:
    chdir: 'dir1'

but it failed (rm could not find files in the directory).

I also tried:

file_regex: '.*?_(?!2)[0-9]{2,}\.(dat|DAT)'

- name: find files
  find:
    paths: "dir1"
    patterns: "{{ file_regex }}"
    use_regex: yes
    recurse: yes
  register: found_files

- name: delete files
  file:
    path: '{{ item.path }}'
    state: absent
  with_items: '{{ found_files.files }}'

but seems like no file is found. The output is:

13:15:30 TASK [myrole : find files]
...
13:15:30 Wednesday 30 January 2019  14:15:30 +0200 (0:00:01.008)       0:00:40.241 *****
13:15:30 ok: [xxx.xxx.xxx.xxx.xxx] => {"changed": false, "examined": 483, "files": [], "matched": 0, "msg": ""}
13:15:30 
13:15:30 TASK [myrole : delete files]
...
13:15:30 Wednesday 30 January 2019  14:15:30 +0200 (0:00:00.350)       0:00:40.592 ***** 
13:15:30 

Upvotes: 1

Views: 4939

Answers (2)

santosh verma
santosh verma

Reputation: 294

As we noticed there are some challenges with regex, delete and copy module. So we can try with shell or command module as given.

  - name:  Delete all tar files from /var/log/
    become: true
    command_warnings=false
    command: "rm -f /var/log/*.tar”

Upvotes: 0

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68239

patterns argument is of list type. If Ansible detects a string, it is converted to list using comma as separator. So you end up with two patterns:

        "patterns": [
            ".*?_(?!2)[0-9]{2",
            "}\\.(dat|DAT)"
        ],

To overcome this, pass your pattern as a list:

- name: find files
  find:
    paths: "dir1"
    patterns:
      - "{{ file_regex }}"
    use_regex: yes
    recurse: yes
  register: found_files

Upvotes: 1

Related Questions