Ubuntu – Delete all files except files with the extension pdf in a directory

bashcommand line

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.

Best Answer

  • 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