Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove files without certain extension?

Tags:

linux

shell

How to remove all files without the .txt and .exe extensions recursively in the current working directory? I need a one-liner.

I tried:

find . ! -name "*.txt" "*.exe" -exec rm -r {} \
find -type f -regextype posix-extended -iregex '.*\.(txt|exe)$'
like image 269
R. Naired Avatar asked Jan 30 '17 12:01

R. Naired


People also ask

How do I delete all files except a specific file extension?

Microsoft Windows Browse to the folder containing the files. Click the Type column heading to sort all files by the type of files. Highlight all the files you want to keep by clicking the first file type, hold down Shift , and click the last file.

How do I delete a file without an extension?

Use Del *. in batch file to remove files with no extension. use Dir /A-D *. to list down all files with no extension.

How do you remove all files except some?

Using Extended Globbing and Pattern Matching Operators Also, with the ! operator, we can exclude all files we don't want glob to match during deletion. Let's look at the list of pattern matching operators: ?(pattern-list) matches at least zero and at most one occurrence.


2 Answers

Try this.

find . -type f ! -name "*.exe" ! -name "*.txt" -exec rm {} \;

The above command will remove all the files other than the .exe and .txt extension files in the current directory and sub directory recursively.

like image 147
sureshkumar Avatar answered Sep 20 '22 14:09

sureshkumar


If you have GNU find with the -delete action:

find . -type f ! \( -name '*.txt' -o -name '*.exe' \) -delete

And if not:

find . -type f ! \( -name '*.txt' -o -name '*.exe' \) -exec rm -f {} +

using -exec ... {} + to execute rm as few times as possible, with the arguments chained.

like image 44
Benjamin W. Avatar answered Sep 21 '22 14:09

Benjamin W.