AppleScripted file contents search using grep

This is a workaround for the Finder insisting on starting a search of the entire HDD on every new search rather than the good ol’ days of 10.3 which was to search in the directory you were staring at. I know you can click a button to switch it, but every time? No, I like the old way better.

No per-instance recursive option, but it’s easy enough to enable it if that is your preferred method.

property search_prompt : "Enter search text."
property search_string : ""
property is_recursive : false

tell application "Finder"
    set this_folder to folder of front window as alias
    if is_recursive is false then
      set the_items to name of every item of this_folder whose kind is not folder as text
      set the_items to {""}
    end if
  end try
end tell

  set the_search to text returned of (display dialog search_prompt default answer search_string) as text
  set search_string to the_search
  set the_results to "'" & the_search & "' found in these files:" & return & return
  set is_found to false
  repeat with i in the_items
    set _grep to ""
      set _grep to do shell script "grep -ilr '" & the_search & "' " & "'" & POSIX path of this_folder & i & "'"
    end try
    if _grep is not "" then
      set is_found to true
      set the_results to the_results & _grep & return
    end if
  end repeat
  if is_found is true then
    set what_now to button returned of (display dialog the_results buttons {"Retry", "OK"})
    if what_now is "OK" then
      exit repeat
    end if
    set search_prompt to "No matches."
  end if
end repeat

If saved as an application you can place it in the Finder’s toolbar for easy launching.

Leave a Reply

Your email address will not be published. Required fields are marked *