Delete all files with a specific extension in a particular directory

A specific directory, say


contains many files. Plenty of these files have the same extension, say .txt.

What code will delete all files in the stated directory with a .txt extension, but leave all others.

Have you checked the “Filesystem” commands:

1 Like

I did see see “rm” and “mkpath”. And deleting a single file from a specified directory looked simple enough, but specifying all files in that directory with a specific extensions for deletion, was not clear to me.

You could do something like: filter(x->endswith(x, ".txt"), readdir(dir)) to get a list of all the “*.txt” files in the directory (assuming you don’t have folders in the directory that end with “.txt”).

Deleting all files that match a pattern is really more of a shell operation. All(?) programming languages I’ve worked with give you a command to delete a single, and leave it up the programmer to delete each file individually.

This doesn’t work yet, but in version 1.5 you can write

foreach(rm, filter(endswith(".txt"), readdir()))  # untested

which is becoming quite concise.


That works!

To delete all text files in a particular directory, it slightly elongates to

foreach(rm, filter(endswith(".txt"), readdir(dir,join=true)))