Can I use AppleScript to delete files on NAS listed in a file?
I am cleaning up my iTunes folders. I realized that there are more than 3k of files which are actually not in iTunes. I identified them and I have all of them inside a text file called "untitled.txt" in the format below.
/Volumes/Multimedia/Music/ITunes Media/Kiko/Come On Up/Come On Up.mp3
/Volumes/Multimedia/Music/ITunes Media/Kiko/Traxxxx/Traxxxx.mp3
The files are sitting on my NAS so my question would be what would the script look like and will it read the NAS file format (I think it is ext4
).
Solution 1:
As an alternative to using AppleScript, it is so much easier just to do it in Terminal using bash
, e.g.:
while IFS= read -r line; do echo rm "$line"; done < /path/to/untitled.txt
Run it as is with the echo
command to have a look1 at its output, and if it look okay, then run the command again without echo
in it.
Note that when run without the echo
command, the path file names will be quoted, so while with echo
command will show as e.g.:
rm /Volumes/Multimedia/Music/ITunes Media/Kiko/Come On Up/Come On Up.mp3
However, without the echo
command, the rm
command with the path file names will execute as e.g.:
rm "/Volumes/Multimedia/Music/ITunes Media/Kiko/Come On Up/Come On Up.mp3"
Thus handling path file names that contains spaces.
1Hint: Enlarge the window in Terminal so you see the full line without it wrapping on the screen as this will make it easier to see any anomalies, if any.
Solution 2:
However, if you do prefer to use an AppleScript solution, this following AppleScript code should do the trick.
This AppleScript code works for me using the latest version of macOS Mojave.
set filePathsTextFile to "/path/to/untitled.txt"
set posixFiles to readFile(filePathsTextFile)
tell application "Finder"
repeat with i in posixFiles
try
set thisItem to i as POSIX file as alias
delete thisItem
on error errMsg number errNum
activate
display alert "Cannot Locate File To Be Deleted" message ¬
errMsg & " Error Code. " & errNum & linefeed & linefeed ¬
& "Please Make Sure The Volume Containing File To Be Deleted Is Mounted Or File Exists" as ¬
critical buttons {"OK"} giving up after 10
return
end try
end repeat
end tell
on readFile(filePathsTextFile)
set theFile to filePathsTextFile
set theParagraphs to read theFile as text using delimiter linefeed
end readFile