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
- 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
- The
find
command can execute actions usingxargs
(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
- Using
-exec
withinfind
:
find . -name "*.pdf" -type f -exec rm {} +
- 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
Corrected approach using find
:
find . -name "*.pdf" -type f -delete
Alternative approaches:
find . -name "*.pdf" -type f | xargs rm
find . -name "*.pdf" -type f -exec rm {} +
Top comments (0)