Monday, May 6, 2024
67
rated 0 times [  67] [ 0]  / answers: 1 / hits: 35748  / 3 Years ago, tue, september 7, 2021, 10:01:39

I have a directory that contains the following:



x.pdf
y.zip
z.mp3
a.pdf


I want to delete all files apart from x.pdf and a.pdf. How do I do this from the terminal? There are no subdirectories so no need for any recursion.


More From » command-line

 Answers
6
cd <the directory you want>
find . -type f ! -iname "*.pdf" -delete


  • The first command will take you to the directory in which you want to delete your files

  • The second command will delete all files except with those ending with .pdf in filename




For example, if there is a directory called temp in your home folder:


cd ~/temp

then delete files:


find . -type f ! -iname "*.pdf" -delete

This will delete all files except xyz.pdf.


You can combine these two commands to:


find ~/temp -type f ! -iname "*.pdf" -delete



. is the current directory. ! means to take all files except the ones with .pdf at the end. -type f selects only files, not directories. -delete means to delete it.


NOTE: this command will delete all files (except pdf files but including hidden files) in current directory as well as in all sub-directories. ! must come before -name. simply -name will include only .pdf, while -iname will include both .pdf and .PDF


To delete only in current directory and not in sub-directories add -maxdepth 1:


find . -maxdepth 1 -type f ! -iname "*.pdf" -delete

[#22208] Wednesday, September 8, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
vigorousom

Total Points: 394
Total Questions: 96
Total Answers: 110

Location: Pitcairn Islands
Member since Fri, Oct 15, 2021
3 Years ago
;