2

In Terminal.app, how can I delete all files of a certain name except for one extension? For example if I have:

File.docx
File.ppt
File.pdf
File.xlsx
File.out
File.app
FIle.otherextension
File2.docx
File2.ppt
File2.pdf
File2.xlsx
File2.out
File2.app
FIle2.otherextension

all in one directory, how can I delete all of the File ones except for File.out?

Expected ls output at the end:

File.out
File2.docx
File2.ppt
File2.pdf
File2.xlsx
File2.out
File2.app
FIle2.otherextension
1

The following will delete all files named File (and only those) within the current folder, except ones with extension .out:

find . -type f \( -iname "File.*" ! -iname "*.out" \) -delete -maxdepth 1

If you want to perform this operation recursively (traversing all subfolders), remove -maxdepth 1:

find . -type f \( -iname "File.*" ! -iname "*.out" \) -delete

The i in -iname performs a case-insensitive search, so file.*, FILE.*, etc. will be deleted as well. Likewise, file.OUT would be spared.

1

Try this:

ls File.* | fgrep -v .out | xargs rm

This corresponds to your description: select all files named File with some extension, remove the one with extension .out from the list, and delete the others.

0

Using ksh's extended glob.

rm !(*.out|File2.*|FIle2.*)

Which says in words- remove files that do not end in .out or begin with File2. or begin with FIle2.

ksh extended glob is also available in bash. You must turn on the option with shopt -s extglob. This solution will fail if you exceed ARG_MAX.

Make sure that you are in the directory where these file exist or you could unintentionally remove files.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .