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.
cd <the directory you want>
find . -type f ! -iname "*.pdf" -delete
.pdf
in filenameFor 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.
!
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
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments