Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove all files containing a certain name within a directory

Tags:

ansible

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?

like image 624
user301693 Avatar asked Aug 21 '15 18:08

user301693


People also ask

How do I delete multiple files with same name?

Browse to the folder with the offending file, hit Shift + Right Click, and select Open a command window here. Now, input dir /x to see a list of shortened file names rather than the full-length version. From the same Command Prompt window, you can now delete the files using the short name.

How delete all files by name in Linux?

Type the rm command, a space, and then the name of the file you want to delete. If the file is not in the current working directory, provide a path to the file's location. You can pass more than one filename to rm . Doing so deletes all of the specified files.

How do I delete all files from a certain type?

You can do this using the Windows GUI. Enter "*. wlx" in the search box in explorer. Then after the files have been found, select them all (CTRL-A) and then delete using the delete key or context menu.

How do I remove all ends with certain string in Linux?

Using rm Command To remove a file with a particular extension, use the command 'rm'. This command is very easy to use, and its syntax is something like this. In the appropriate command, 'filename1', 'filename2', etc., refer to the names, plus their full paths.


1 Answers

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
like image 185
MillerGeek Avatar answered Nov 02 '22 06:11

MillerGeek