DEV Community

Pavol Z. Kutaj
Pavol Z. Kutaj

Posted on

How to Recursively Delete PDF Files in Bash using `find`

USECASE

The aim of this page📝 is to explain how to recursively delete PDF files using the find command in Bash. Cleaning up some learning materials from Pluralsight. Want to delete slides, but keep the code. I'm learning about the find command which I understand is a powerful filter on the file system (name, time, extension) which directly supports acting on the matches. My first impression is that it goes a bit against Unix philosophy (do 1 thing — here find is not just finding, but also acting), but I understand that piping into other commands adds extra complications because the output is not a string, but a structure.

  • Initially, I've tried rm -rf *.pdf command
  • That only targets files in the current directory.
  • To recursively delete PDF files in subdirectories, use the find command.
  • Example of a safer way to delete PDF files:
find . -name "*.pdf" -type f -delete
Enter fullscreen mode Exit fullscreen mode
  • Explanation of the find command options:
    • .: Specifies the current directory.
    • -name "*.pdf": Searches for files with the .pdf extension.
    • -type f: Ensures only files (not directories) are targeted.
    • -delete: Removes the files found.
  • The find command is versatile and can search by name, pattern, type, size, and time.
  • Example to find .txt files modified in the last 7 days:
find . -name "*.txt" -type f -mtime -7
Enter fullscreen mode Exit fullscreen mode
  • The find command can execute actions using xargs (can't just pipe it into rm, because that would treat whole output as a single string and everything is a string by default in bash):
find . -name "*.pdf" -type f | xargs rm
Enter fullscreen mode Exit fullscreen mode
  • Using -exec within find:
find . -name "*.pdf" -type f -exec rm {} +
Enter fullscreen mode Exit fullscreen mode
  • Both xargs and -exec handle the array of filenames effectively.
  • Using these commands ensures rm is run on each found item.

Code Examples

User's initial attempt:

rm -rf *.pdf
Enter fullscreen mode Exit fullscreen mode

Corrected approach using find:

find . -name "*.pdf" -type f -delete
Enter fullscreen mode Exit fullscreen mode

Alternative approaches:

find . -name "*.pdf" -type f | xargs rm
Enter fullscreen mode Exit fullscreen mode
find . -name "*.pdf" -type f -exec rm {} +
Enter fullscreen mode Exit fullscreen mode

Top comments (0)