Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete files from directory if filename contains a certain word

I need to check a directory to see if there are any files whose file name contains a specific keyword and if there are, to delete them. Is this possible?

For example, delete all existing files in "C:\Folder" whose file name contains the keyword "Apple".

like image 477
user Avatar asked Oct 25 '09 08:10

user


People also ask

How do I delete a file with a specific 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 remove a file with the name '- something?

How do I remove or access a file with the name '-something' or containing another strange character ? If your file starts with a minus, use the -- flag to rm; if your file is named -g, then your rm command would look like rm -- -g.

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.


1 Answers

To expand on Henk's answer, you need:

string rootFolderPath = @"C:\\SomeFolder\\AnotherFolder\\FolderCOntainingThingsToDelete"; string filesToDelete = @"*DeleteMe*.doc";   // Only delete DOC files containing "DeleteMe" in their filenames string[] fileList = System.IO.Directory.GetFiles(rootFolderPath, filesToDelete); foreach(string file in fileList) {     System.Diagnostics.Debug.WriteLine(file + "will be deleted"); //  System.IO.File.Delete(file); } 

BE VERY CAREFUL!

Note that I've commented out the delete command. Run it and test it carefully before you let it actually delete anything!

If you wish to recursively delete files in ALL subfolders of the root folder, add ,System.IO.SearchOption.AllDirectories); to the GetFiles call.

If you do this it is also a very good idea to refuse to run if the rootFolderPath is less than about 4 characters long (a simple protection against deleting everything in C:\ - I've been there and done that and it's not fun!!!)

like image 53
Jason Williams Avatar answered Sep 21 '22 05:09

Jason Williams