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 *.pdfcommand - That only targets files in the current directory.
 - To recursively delete PDF files in subdirectories, use the 
findcommand. - Example of a safer way to delete PDF files:
 
find . -name "*.pdf" -type f -delete
- Explanation of the 
findcommand 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 
findcommand 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 
findcommand 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 
-execwithinfind: 
find . -name "*.pdf" -type f -exec rm {} +
- Both 
xargsand-exechandle the array of filenames effectively. - Using these commands ensures 
rmis 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)