I want to go through a hard drive and delete files of a certain extension
I’ve found this
tell application “Finder”
delete (every file of item “Macintosh HD” whose name extension is “bpn”)
empty trash – comment out to be sure not to delete wrong files
end tell
This would be fine but only deletes items at the root of the disk. How do I get it to go through the entire directory structure?
Don’t forget to use both find’s -print0 flag and xargs’s -0 flag when using the two commands together, if you need newline characters to be command argument delimiters. (Analagous to your “{} ;” escaping.) Normally, spaces are command delimiters to xargs, but that will screw up your xargs’ed command (especially dangerous when using rm to delete files). Quick overview of what the two flags do:
find: -print0
This tells the find command to print the path name and append a ASCII NUL character to the end of the string. (This is a \0 character code.)
xargs: -0
This tells xargs that its argument delimiter is an ASCII NUL character, \0.
Example usage:
find / -name "*.bpn" -print0 | xargs -0 rm
Or, with output example:
thermodynamics:~/Projects/- Parts mikey$ find . -name "*.h" -print0 | xargs -0 grep "import"
./DotMacKit.framework/Versions/A/Headers/DMAccount.h:#import <Foundation/Foundation.h>
./DotMacKit.framework/Versions/A/Headers/DMAccount.h:#import <DotMacKit/DMCredential.h>
./DotMacKit.framework/Versions/A/Headers/DMAccount.h:#import <DotMacKit/DMPrincipal.h>
./DotMacKit.framework/Versions/A/Headers/DMCredential.h:#import <Foundation/Foundation.h>
[similar output continued for many, many lines]
Interesting link Mikey thank you… Typically I have aways used -exec, but on a few projects I went with xargs for various reasons. It’s nice to see a summary though of the differences.
Using the Finder to scan the extensions of your entire startup disk will take a very long time. Even a shell script will. If these files can be found in Spotlight however there’s a faster way:
Run this script, choose a sample file, and copy the text without the quotes of IK from the Results pane of your Script Editor
set f to choose file
set Sample to (do shell script "mdls " & quoted form of POSIX path of f)
set tid to AppleScript's text item delimiters
set AppleScript's text item delimiters to "kMDItemKind" as Unicode text
set IK to paragraph 1 of (text item 2 of Sample)
set AppleScript's text item delimiters to tid
IK
Now run this one, pasting the text from the first between the quotes in the first line of it.
set IK to "" as Unicode text
set F to paragraphs of (do shell script "mdfind -onlyin / \"kMDItemKind == '" & IK & "'\"")
set P to {}
repeat with aF in F
set P's end to (POSIX file aF) as alias
end repeat
P -- the list of every file of that kind. Finder delete them so they'll go to the trash.
Just loop through P in the Finder to move them all to the trash where you can examine them before they’re gone.
PS: James, these could be combined, but I don’t have time.