Cowboy's Applescripts

Color Picker v 1.0

Energy Saver Dimmer Reset v 1.1

Finder Copy Open Window Paths v 1.1

Finder Copy Path of File v 1.1

Finder Open Terminal Here v 1.1

Linkinus Maximize v 1.0

Linkinus Minimize v 1.0

Mail.app Junk and Delete v 1.1

Mail.app Toggle Flagged Status v 1.0

Mail.app Unread Mailbox Selector v 1.0

Open-Delete Temp Downloads Folder Action v 1.1

Safari add www. & .com to URL v 1.0

Safari Copy TinyURL to Clipboard v 1.2

Safari Embedded Media Launcher v 1.10

Safari Open Page in Firefox v 1.0

Safari URL Up One Level v 1.0

Safari URL Up to Top Level v 1.0

NOTE: If you're running 10.3 or newer, you should click •• links to open that script directly in Script Editor (because of possible line wrapping issues, that method is preferable over copying & pasting directly from this page).

Also, these scripts have only been tested in 10.4 and 10.5, so your mileage may vary with different versions of OS X.

And since I've mentioned it in some of my script comments, I'll mention again that I use FastScripts, a fantastic replacement for the built-in OS X Script Menu that allows setting per-app and global keybinds, among other things!

Comments? Suggestions? Let me know in my forums, thanks! - Cowboy


Color Picker v 1.0 ••

(*

   Color Picker v 1.0 - 2/1/2008
   by "Cowboy" Ben Alman - http://benalman.com/

   I used to open TextEdit and press Cmd-Shift-C just for the Color
   Picker, but I figured there had to be a better way to do it.. so I
   wrote this super-simple Color Picker AppleScript.
   
   In addition to picking a color, you can copy its #hex value to the
   clipboard (and exit) by clicking the "Ok" button.
   
   Recommended for use with FastScripts script menu,
   with a hotkey bound to it, for easy access!
   
*)

property rgbColor : {65535, 0, 0}

set rgbColor to (choose color default color rgbColor)
set hexColor to my rgb2hex(rgbColor)
set the clipboard to hexColor

on rgb2hex(rgb)
   set hex to "#"
   repeat with i from 1 to the count of rgb
      set hex to hex & (do shell script "printf '%02X\\n' $(echo '" & (item i of rgb) & " / 256' | bc)")
   end repeat
   return hex
end rgb2hex

Energy Saver Dimmer Reset v 1.1 ••

(*

   Energy Saver Dimmer Reset v 1.1 - 2/6/2008
   by "Cowboy" Ben Alman - http://benalman.com/

   Since upgrading to OS X 10.5, my Macbook Pro display automatically
   dims after just a few minutes, even if I have 'Automatically reduce
   the brightness of the display before display sleep' in the Energy
   Saver System Preferences pane unchecked.
   
   The only way I've found to fix this problem is to check and uncheck
   that option, but this 'fix' seems to get reset every time the computer
   comes out of sleep.
   
   So.. I just run this script every time I wake the system. What fun!
   
   Either way, I think this is a pretty good example of a 'do shell script
   as root' AppleScript, so feel free to use/modify it for your own needs.
   
   Recommended for use with FastScripts script menu,
   with a hotkey bound to it, for easy access!
   
*)

property pwd : false

set dialogTitle to "Energy Saver Dimmer Reset"

if pwd is false then
   display dialog "Password:" with title dialogTitle default answer "" with hidden answer
   set pwd to text returned of result
end if

set success to false

repeat until success is true
   try
      -- shell script to be run as root
      set cmd to "pmset halfdim 0 && pmset halfdim 1 && pmset halfdim 0"
      
      do shell script cmd password pwd with administrator privileges
      set success to true
      beep
      display dialog "Success!" with title dialogTitle buttons {"Ok"} default button 1 giving up after 3
   on error
      set pwd to false
      set pwd to display dialog "Sorry, try again. Password:" with title dialogTitle default answer "" with hidden answer
      set pwd to text returned of result
   end try
end repeat

Finder Copy Open Window Paths v 1.1 ••

(*

   Finder Copy Open Window Paths v 1.1 - 7/30/2007
   by "Cowboy" Ben Alman - http://benalman.com/

   In any Open/Save dialog, you can press Cmd-Shift-G to display the
   "Go to the folder" dialog. Instead of typing in a path manually, you
   can run this script to choose from the paths of all the open Finder
   windows.

   From that dialog, make a selection to copy that path to the clipboard,
   and then paste it into the "Go to the folder" dialog!

   Using FastScripts, I have this script bound to Cmd-Opt-Shift-G
   so that I can very easily press Cmd-Shift-G then Cmd-Opt-Shift-G
   in any Open/Save dialog to open both.

   I use this script instead of Default Folder X now!

*)

set allPaths to {}

tell application "Finder"
   set allwindows to (every Finder window)
   
   if allwindows is not {} then
      repeat with thisWindow in allwindows
         try
            set thisWindowPath to the POSIX path of (target of thisWindow as alias)
            if thisWindowPath is not in allPaths then
               set allPaths to allPaths & thisWindowPath
            end if
         end try
      end repeat
   else
      display dialog "No open Finder windows" with icon stop buttons {"Bloops!"} default button 1
      return
   end if
end tell

set strPath to choose from list allPaths with prompt "Copy the path of a Finder window:" default items item 1 of allPaths without multiple selections allowed

if strPath is not false then
   set the clipboard to item 1 of strPath
end if

Finder Copy Path of File v 1.1 ••

(*

   Finder Copy Path of File v 1.1 - 5/7/2005
   by "Cowboy" Ben Alman - http://benalman.com/

   Drop a file on this script to copy its path to the clipboard, or just run
   it to copy the path of the currently selected item in the Finder.
   
   Great when bound to a hotkey in FastScripts or added
   to the Finder Sidebar for drag-drop functionality!

*)

tell application "Finder"
   try
      if exists front window then
         my copy_path((first item of (get selection as list)) as alias)
      end if
   end try
end tell

on open these_items
   my copy_path((first item of these_items) as alias)
end open

on copy_path(strPath)
   try
      set strPath to the POSIX path of strPath
      if strPath is not "" then
         display dialog "Current path copied to clipboard:" & return & strPath buttons {"Sweet!"} default button 1
         set the clipboard to strPath
      end if
   end try
end copy_path

Finder Open Terminal Here v 1.1 ••

(*

   Finder Open Terminal Here v 1.1 - 2/1/2008
   by "Cowboy" Ben Alman - http://benalman.com/

   Drop a folder on this script (or just run it) to open a new
   Terminal window there. If the selected item isn't a folder,
   it will open the item's parent folder.
   
   Great when bound to a hotkey in FastScripts or added
   to the Finder Sidebar for drag-drop functionality!

*)


tell application "Finder"
   try
      my open_terminal((first item of (get selection as list)) as alias)
   on error
      my open_terminal(desktop as alias)
   end try
end tell

on open these_items
   my open_terminal((first item of these_items) as alias)
end open

on open_terminal(strPath)
   try
      try
         set strPath to strPath as alias
         set strPath to POSIX path of strPath
      end try
      
      set strPath to do shell script "echo " & (quoted form of strPath) & " | perl -p -e 's/(.*\\/).*/$1/'"
      
      if strPath is not "" then
         tell application "System Events"
            set termExists to (exists process "Terminal")
         end tell
         tell application "Terminal"
            activate
            if termExists then
               do script "cd " & quoted form of strPath
            else
               do script "cd " & quoted form of strPath in window 1
            end if
         end tell
      end if
   end try
end open_terminal


Linkinus Maximize v 1.0 ••

(*
   Linkinus Maximize v 1.0 - 7/31/2007
   by "Cowboy" Ben Alman - http://benalman.com/
   
   Save as ~/Library/Application Support/Linkinus/Scripts/max.scpt and type /reload
   to install. Run by typing /max in Linkinus.
   
*)

on linkinuscmd()
   tell application "System Events"
      if UI elements enabled then
         tell process "Linkinus"
            click button 2 of window 1
         end tell
      else
         tell application "System Preferences"
            activate
            set current pane to pane "com.apple.preference.universalaccess"
            display dialog "UI element scripting is not enabled. Please check \"Enable access for assistive devices\" and try again." with icon stop buttons {"Bloops!"} default button 1
         end tell
      end if
   end tell
   
   return ""
end linkinuscmd

Linkinus Minimize v 1.0 ••

(*
   Linkinus Minimize v 1.0 - 7/31/2007
   by "Cowboy" Ben Alman - http://benalman.com/
   
   Save as ~/Library/Application Support/Linkinus/Scripts/min.scpt and type /reload
   to install. Run by typing /min in Linkinus.
   
*)

on linkinuscmd()
   tell application "System Events"
      if UI elements enabled then
         tell process "Linkinus"
            click button 3 of window 1
         end tell
      else
         tell application "System Preferences"
            activate
            set current pane to pane "com.apple.preference.universalaccess"
            display dialog "UI element scripting is not enabled. Please check \"Enable access for assistive devices\" and try again." with icon stop buttons {"Bloops!"} default button 1
         end tell
      end if
   end tell
   
   return ""
end linkinuscmd

Mail.app Junk and Delete v 1.1 ••

(*

   Mail.app Junk and Delete v 1.1 - 8/06/2007
   by "Cowboy" Ben Alman - http://benalman.com/

   When triggered, this script marks the selected messages as
   junk and read, and then deletes them. It won't junk/delete
   flagged messages, as I manage most of my email from a
   Smart Folder that just shows Flagged & Unread emails, and
   want to avoid accidents wherever possible.

   Recommended for use with FastScripts script menu,
   with a hotkey bound to it, for easy access!

*)

tell application "Mail"
   try
      set theMessages to selection
      if (theMessages is not {}) then
         
         set allJunk to true
         
         repeat with theMessage in theMessages
            if the flagged status of theMessage is true then
               set allJunk to false
            else
               set the junk mail status of theMessage to true
               set the read status of theMessage to true
            end if
         end repeat
         
         if allJunk is true then
            -- delete selected messages without losing the cursor position
            tell application "System Events"
               tell process "Mail"
                  key code 51
               end tell
            end tell
         end if
      else
         beep
         display dialog "No message selected" with icon stop buttons {"Bloops!"} default button 1
      end if
   end try
end tell

Mail.app Toggle Flagged Status v 1.0 ••

(*

   Mail.app Toggle Flagged Status v 1.0 - 11/27/2005
   by "Cowboy" Ben Alman - http://benalman.com/

   When triggered, this script toggles the flagged status
   of the selected message or messages in Mail.

   Recommended for use with FastScripts script menu,
   with a hotkey bound to it, for easy access!

*)

tell application "Mail"
   try
      set theMessages to selection
      if (theMessages is not {}) then
         
         set allFlagged to true
         
         repeat with theMessage in theMessages
            set isFlagged to the flagged status of theMessage
            set allFlagged to allFlagged and isFlagged
         end repeat
         
         if allFlagged then
            set newFlaggedStatus to false
         else
            set newFlaggedStatus to true
         end if
         
         repeat with theMessage in theMessages
            set the flagged status of theMessage to newFlaggedStatus
         end repeat
      else
         beep
         display dialog "No message selected" with icon stop buttons {"Bloops!"} default button 1
      end if
   end try
end tell

Mail.app Unread Mailbox Selector v 1.0 ••

(*

   Mail.app Unread Mailbox Selector v 1.0 - 5/5/2005
   by "Cowboy" Ben Alman - http://benalman.com/

   When triggered, this script tries to:
   
      - Activate an open main window OR
       Un-minimize the minimized main window OR
       Create a new main window
      
      - Select the first mailbox with unread messages OR
       Select the mailbox set as defaultMailbox

   Recommended for use with FastScripts script menu,
   with a hotkey bound to it, for easy access!

*)

tell application "Mail"
   
   set defaultMailbox to mailbox "Cowboy"
   --set defaultMailbox to inbox
   
   
   try
      -- activate existing main window, or create a new one if necessary
      set allwindows to (every message viewer)
      
      if (the (count of allwindows) = 0) then
         set theWindow to make message viewer
      else
         set theWindow to front message viewer
      end if
      
      set the miniaturized of theWindow to false
      activate
      
      -- select first mailbox with unread messages
      set allMailboxes to (every mailbox)
      set allMailboxes to allMailboxes & {inbox}
      repeat with currentMailbox in allMailboxes
         if (unread count of currentMailbox is not 0) then
            set selected mailboxes of theWindow to {currentMailbox}
            return
         end if
      end repeat
      
      -- if no unread messages, select defaultMailbox
      set selected mailboxes of theWindow to {defaultMailbox}
   end try
end tell

Open-Delete Temp Downloads Folder Action v 1.1 ••

(*

   Open/Delete Temp Downloads Folder Action v 1.1 - 6/14/2005
   by "Cowboy" Ben Alman - http://benalman.com/

   This is a folder action that I attach to my Safari Downloads folder
   that will automatically open, delete, or open then delete files with
   specified extensions. I have 'Open "safe" files after downloading'
   disabled for other reasons, but there are still files I want to open
   automatically. I find it especially useful for auto-launching Real or
   Windows Media playlist files, then cleaning up!
   
   For more information on Folder Actions, including instructions for
   setting them up, please visit Apple's "AppleScript in Mac OS X"
   website: http://www.apple.com/applescript/folderactions/

*)

on adding folder items to this_folder after receiving added_items
   
   
   set open_then_delete to {"rm", "ram", "m3u", "asf", "wmv"}
   set just_delete to {}
   set just_open to {}
   
   set time_before_delete to 20 -- time in seconds
   
   
   try
      repeat with theItem in added_items
         set theFileExt to the name extension of the (info for theItem)
         if theFileExt is in (open_then_delete & just_delete & just_open) then
            tell application "Finder"
               if theFileExt is in (open_then_delete & just_open) then
                  open theItem
               end if
               if theFileExt is in (open_then_delete & just_delete) then
                  do shell script "(sleep " & time_before_delete & "; rm " & quoted form of (POSIX path of theItem) & ") > /dev/null 2>&1 &"
               end if
            end tell
         end if
      end repeat
   end try
end adding folder items to

Safari add www. & .com to URL v 1.0 ••

(*

   Safari add www. & .com to URL v 1.0 - 11/01/2005
   by "Cowboy" Ben Alman - http://benalman.com/

   When triggered, this script will grab the unfinished URL
   you've started typing into the address bar, and load a
   (hopefully) more useful URL:
   
   http://www.TEXT_YOU_TYPED.com

   The one major difficulty here is that the unfinished URL
   you've started typing into the address bar is not readily
   accessible, and you need to use a tool like the PreFab
   UI Browser (www.prefab.com/uibrowser/) to find out
   exactly how to access it if you've changed the toolbar
   from its default setup.
   
   Once you have the AppleScript code to "Get Value of
   Selected Element" with Reference Form "Index" you
   can just use it in the "set newAddress to..." line below.   
   
*)

try
   tell application "System Events"
      tell application process "Safari"
         set newAddress to (value of text field 1 of splitter group 1 of group 4 of tool bar 1 of window 1)
      end tell
   end tell
   
   tell application "Safari"
      set currentDocument to the document of window 1
      set the URL of currentDocument to "http://www." & newAddress & ".com"
   end tell
end try

Safari Copy TinyURL to Clipboard v 1.2 ••

(*

   Safari Copy TinyURL to Clipboard v 1.2 - 7/13/2005
   by "Cowboy" Ben Alman - http://benalman.com/

   When triggered, this script will get a TinyURL for the
   current Safari window's active page, then copy it to
   the clipboard. (see www.tinyurl.com for more info)
   
   Recommended for use with FastScripts script menu,
   with a hotkey bound to it, for easy access!

*)

tell application "Safari"
   try
      set currentDocument to the document of window 1
      set currentURL to (URL of currentDocument) as string
      
      set currentURL to do JavaScript "escape('" & currentURL & "')" in currentDocument
      
      set tinyURL to do shell script "echo `curl -s -m 30 \"http://tinyurl.com/create.php\" -d url=\"" & currentURL & "\" | grep \"input type=hidden name=tinyurl\" | sed 's_.*\"\\(.*\\)\".*_\\1_'`"
      
      if tinyURL is not "" then
         display dialog "TinyURL copied to clipboard:" & return & return & tinyURL buttons {"Sweet!"} default button 1
         set the clipboard to tinyURL
      end if
      
   on error
      return
   end try
end tell

Safari Embedded Media Launcher v 1.10 ••

(*

   Safari Embedded Media Launcher v 1.10 - 11/19/2005
   by "Cowboy" Ben Alman - http://benalman.com/

   When triggered, this script searches the current web page
   and any subframes looking for certain linked or embedded
   media files. It then returns a dialog where you can choose
   the file you want to open. In addition, you can choose to
   perform an additional action on the source web page, like
   closing it or going back one page in its history.
   
   The script looks at the name of the current document as
   well as in specific attributes of certain tags:
      <param value='...
      <embed src='...
      <a href='...
      <ref href='...

   Currently supported media files and their app:
      .mov .mpg .mpeg .avi - QuickTime Player
      .wav .mp3 .m3u .aif .aiff - iTunes
      .ram .rm - RealOne Player
      .asx .asf .wmv - Windows Media Player

   Recommended for use with FastScripts script menu,
   with a hotkey bound to it, for easy access!

*)

global QT_ext, iTunes_ext, Real_ext, WMP_ext

set QT_ext to {"mov", "mpg", "mpeg", "mp4", "avi"}
set iTunes_ext to {"wav", "mp3", "m3u", "aif", "aiff"}
set Real_ext to {"ram", "rm"}
set WMP_ext to {"asx", "asf", "wmv"}

set theExtensions to QT_ext & iTunes_ext & Real_ext & WMP_ext

on processURL(theURL)
   set urlExtension to do shell script "echo " & quoted form of theURL & " | sed 's/.*[.]\\([^?&]*\\).*/\\1/'"
   
   if QT_ext contains urlExtension then
      tell application "QuickTime Player"
         activate
         getURL theURL
      end tell
   else if iTunes_ext contains urlExtension then
      tell application "iTunes"
         activate
         open location theURL
      end tell
   else if Real_ext contains urlExtension then
      tell application "RealOne Player"
         activate
         GetURL theURL
      end tell
   else if WMP_ext contains urlExtension then
      tell application "Windows Media Player"
         activate
         open location theURL
      end tell
   end if
end processURL

on numberizeList(theList)
   set tempList to {}
   repeat with i from 1 to count of theList
      set tempList to tempList & {i & ". " & (item i of theList) as string}
   end repeat
   return tempList
end numberizeList

on sendCmdKeyToSafari(theKey)
   tell application "System Events"
      tell process "Safari"
         keystroke theKey using command down
      end tell
   end tell
end sendCmdKeyToSafari

tell application "Safari"
   try
      set currentDocument to the document of window 1
      
      set grepStr to ""
      repeat with theExtension in theExtensions
         if grepStr is not "" then
            set grepStr to grepStr & "\\|"
         end if
         set grepStr to grepStr & theExtension
      end repeat
      
      set grepStr to "[.]\\(" & grepStr & "\\)\\($\\|[?&]\\)"
      
      set HTMLpage to false
      try
         set theSource to the source of currentDocument
         if theSource is not "" then
            set HTMLpage to true
         end if
      end try
      
      set mediaListStr to ""
      
      if HTMLpage is false then
         try
            set mediaListStr to do shell script "echo " & quoted form of (URL of currentDocument as string) & " | grep '" & grepStr & "'"
         end try
      end if
      
      if mediaListStr is "" then
         set grepStr to do shell script "echo '" & grepStr & "' | sed 's/\\\\//g'"
         set mediaListStr to do JavaScript "(function(z,y,x,w){ function x(a,b,c,d,e,f,g,h){ e=a.document.getElementsByTagName(b); for(f=0; f<e.length; f++){ g=e[f].getAttribute(c); if(g&&g.match(d)){ h=a.document.location; z.push((g.match(/^.*:\\/\\//)?g:g.match(/^\\//)?(h.protocol+'//'+h.hostname+g):(h.href.match(/^(.*)\\//)[0])+g))}}}function w(i,j,k,l){ if(typeof i.location.href=='string'){ x(i,'param','value',y); x(i,'embed','src',y); x(i,'a','href',y); x(i,'ref','href',y); j=i.frames; k=j.length; if(k>0){ for(l=0; l<k; l++){ w(j[l])}}}}w(top); return z.join('\\n')})([],/" & grepStr & "/i)" in currentDocument
      end if
      
      set mediaListStr to do shell script "echo " & quoted form of mediaListStr & " | sed '/^$/d' | sort -f | uniq"
      
      set origDelimiters to AppleScript's text item delimiters
      set AppleScript's text item delimiters to {ASCII character 10}
      set mediaList to mediaListStr's paragraphs
      set AppleScript's text item delimiters to origDelimiters
      
      if mediaList is {""} then
         beep
         display dialog "No media found" with icon stop buttons {"Bloops!"} default button 1
         return
      end if
      
      set mediaListNumberized to my numberizeList(mediaList)
      
      set mediaURL to choose from list mediaListNumberized with prompt "Select a media file:" OK button name "Play" default items first item of mediaListNumberized without multiple selections allowed
      
      set mediaURL to item (first word of first item of mediaURL) of mediaList
      
      if mediaURL is false then return
      
      set addtlActions to {"Do nothing", "Close window", "Go back one page", "Go back two pages", "Copy URL to clipboard (don't play)"}
      
      set addtlActions to my numberizeList(addtlActions)
      set addtlAction to choose from list addtlActions with prompt "Perform additional action:" default items first item of addtlActions without multiple selections allowed
      
      if addtlAction is false then return
      
      set addtlAction to first item of addtlAction
      
      if addtlAction is item 2 of addtlActions then
         my sendCmdKeyToSafari("w")
      else if addtlAction is item 3 of addtlActions then
         if HTMLpage then
            do JavaScript "history.go(-1)" in currentDocument
         else
            my sendCmdKeyToSafari("[")
         end if
      else if addtlAction is item 4 of addtlActions then
         if HTMLpage then
            do JavaScript "history.go(-2)" in currentDocument
         else
            my sendCmdKeyToSafari("[")
            my sendCmdKeyToSafari("[")
         end if
      else if addtlAction is item 5 of addtlActions then
         set the clipboard to mediaURL
         return
      end if
      my processURL(mediaURL)
      
   on error
      return
   end try
end tell


Safari Open Page in Firefox v 1.0 ••

(*

   Safari Open Page in Firefox v 1.0 - 12/1/2005
   by "Cowboy" Ben Alman - http://benalman.com/

   When triggered, this script will open the current page
   URL in Firefox. Pretty simple, huh?
   
   Recommended for use with FastScripts script menu,
   with a hotkey bound to it, for easy access!

*)

try
   tell application "Safari"
      set currentDocument to the document of window 1
      set currentURL to (URL of currentDocument) as string
   end tell
   
   tell application "Firefox"
      Get URL currentURL
   end tell
end try

Safari URL Up One Level v 1.0 ••

(*

   Safari URL Up One Level v 1.0 - 5/18/2005
   by "Cowboy" Ben Alman - http://benalman.com/

   When triggered, this script will go up one "level"
   of a website, while keeping the protocol, port, and
   domain the same. For example, for each execution,
   it will change this URL:
   
   http://host.rj3.net/anyfolder/anypage.html?query=string#anchor

   to this:
   
   http://host.rj3.net/anyfolder/anypage.html?query=string
   http://host.rj3.net/anyfolder/anypage.html
   http://host.rj3.net/anyfolder/
   http://host.rj3.net/
   http://rj3.net/
   
   And then, used once more, for good measure:
   
   http://www.rj3.net/

   Recommended for use with FastScripts script menu,
   with a hotkey bound to it, for easy access!
   
   ---
   
   Aside: I've made bookmarklets like this in JavaScript,
   but AppleScripts are more effective on URLs where
   there isn't a DOM, like on .gif or .mov pages.
   
   My JavaScript Bookmarklets:
   http://cowboyscripts.org/?page=bookmarklets

*)


tell application "Safari"
   try
      set currentDocument to the document of window 1
      set currentURL to (URL of currentDocument) as string
      
      set newURL to do shell script "echo " & (quoted form of currentURL) & " | perl -p -e 's/(.*)\\/\\/(?:([^\\/]*\\/)(?:(.*)#.*|(.*)\\?.*|(.*\\/).+|.+)|.*?\\.(.*\\..*)|(.*\\..*))/$1\\/\\/$2$3$4$5$6   $7/;s/   $//;s/   /www./'"
      
      set the URL of currentDocument to newURL
   on error
      return
   end try
end tell

Safari URL Up to Top Level v 1.0 ••

(*

   Safari URL Up to Top Level v 1.0 - 5/18/2005
   by "Cowboy" Ben Alman - http://benalman.com/

   When triggered, this script will go to the top "level"
   of a website, while keeping the protocol, port, and
   domain the same. For example, it will change a URL
   like this:
   
   http://rj3.net/anyfolder/anypage.html?query=string#anchor

   to this:
   
   http://rj3.net/

   Recommended for use with FastScripts script menu,
   with a hotkey bound to it, for easy access!
   
   ---
   
   Aside: I've made bookmarklets like this in JavaScript,
   but AppleScripts are more effective on URLs where
   there isn't a DOM, like on .gif or .mov pages.
   
   My JavaScript Bookmarklets:
   http://cowboyscripts.org/?page=bookmarklets

*)

tell application "Safari"
   try
      set currentDocument to the document of window 1
      set currentURL to (URL of currentDocument) as string
      
      set newURL to do shell script "echo " & (quoted form of currentURL) & " | perl -p -e 's/(.*)\\/\\/(.*?\\/).*/$1\\/\\/$2/'"
      
      set the URL of currentDocument to newURL
   on error
      return
   end try
end tell