Find file pattern containing date and timestamp

Viewed 209

Is there a pattern which I can use when finding my file which contains date and timestamp. The format of my file is file_name.file_extension.processID.YYYY-MM-DD@HH:MM:SS~

My variables

findFile
  - "home/usr/file1"
  - "home/usr/file2"
  - "home/usr/file3/file4"
  - "home/usr/file5"

My playbook role

- name: Find files
  find:
    paths: "{{ item }}"
    patterns:
      - '*.*.*.*.*@*~'
    age: 30d
    recurse: yes
  register: fileList
  loop: "{{ findFile }}"
  
- name: Delete files
  file:
    path: "{{ item.path }}"
    state: absent
  loop: "{{ fileList.files }}"

This is the sample file and directory

home
   |-------usr
             |-------file1
                         |-------configFile.xml
             |-------file2
                         |-------propertiesFile.txt.2012.2020-07-13@23:08:10~
             |-------file3
                         |-------file4
                                     |-------content.yml.2012.2020-04-04@23:08:10~                       
             |-------file5
                         |-------configFile.xml.2012.2020-03-05@13:08:10~
1 Answers

You could use

.*\.\d+\.\d{4}-\d{2}-\d{2}@\d{2}:\d{2}:\d{2}~$

To test it: https://regex101.com/r/8nqFoj/1

  • .* match the file and file extension. You could also do .*\..* if you want to force a file.ext, where this solution also find files without extension.
  • \. match a single dot
  • \d+ match 1 to n digit, for the process ID
  • \. match a single dot
  • \d{4}-\d{2}-\d{2} match the date part: exactly 4 digits, the year, then a dash, then exactly 2 digits, the month, then a dash, then exactly 2 digits, the day
  • @ a single at sign
  • \d{2}:\d{2}:\d{2} match the time part: exactly 2 digits, the hours, then a single colon, then exactly 2 digits, the minutes, then a single colon, then exactly 2 digits, the seconds
  • ~$ the tilde sign that should be the last character of the string, as indicated by the dollar sign ($)
Related