Cleaning the Address Book with AppleScript

I’m weeding out my client address book, dropping contacts who have moved to other companies (unless I can find where they’ve gone) or retired, and fixing out-of-date and incomplete information. It’s a painful process, and one that, for the most part, doesn’t seem amenable to automation.

I have been able to automate one part of the process. I like the entry for my address fields to have a country value of “USA”1 instead of “United States” or “United States of America,” which is what some imported vCards have left me with. I’ve changed these to the form I prefer with this simple AppleScript:

 1:  tell application "Address Book"
 2:    set cl to ""
 3:    repeat with i from 1 to 5
 4:      set changers to (people whose (country of address i) starts with "United States")
 5:      repeat with p in changers
 6:        set country of address i of p to "USA"
 7:      end repeat
 8:    end repeat
 9:    save
10:  end tell

I’m pretty sure I don’t have anyone in my Address Book with five addresses, but I put that value into Line 3 to make sure all the addresses were covered. The script runs fast enough that the extra iterations over nonexistent addresses are barely noticeable.

That the save in Line 9 was necessary was a bit of a surprise. I never Save after editing the Address Book by hand, but I soon learned that my changes didn’t “take” without that line.

I should mention that before writing this script I searched for “United” and found at least a couple of dozen of entries with country fields that weren’t to my liking. If there had been fewer than that—say a dozen or so—I wouldn’t have bothered writing the script. Just making the changes by hand would’ve been faster. Frankly, making the changes by hand might have been faster even with 2-3 dozen non-“USA” entries, but with that many I was able to persuade myself that writing the script was worthwhile.

I usually don’t need much persuading to write a script rather than edit by hand.

  1. This applies, of course, only to clients in the USA. I don’t force a “USA” country entry on my Canadian clients.