Home » Questions » Computers [ Ask a new question ]

Deleting all files that do not match a certain pattern - Windows command line

Deleting all files that do not match a certain pattern - Windows command line

Deleting items via the command-line is pretty easy.

Asked by: Guest | Views: 30
Total answers/comments: 3
Guest [Entry]

"I would do it like this:

attrib +r *.jpg
del /q *
attrib -r *.jpg

This will first make all JPG files read-only, delete everything else (it will automatically skip read-only files), and then make the JPG files writeable again."
Guest [Entry]

"Powershell to the rescue
In times of Windows 7/8 it's the successor of the good old command line

Del C:\myFolder\* -exclude '*.jpg'

Del is an alias for Remove-Item. It has several options like recurse, include, exclude and filter (use this for RegEx)

You have to add \* to include files in a given folder"
Guest [Entry]

"Another way to delete all files matching a filename is shown below. The for loop list's all files and the if NOT matches by filename (without directory name).

for /r %f in (*) do if not %~nxf == abc.xml del ""%f"""