Skip to content

Instantly share code, notes, and snippets.

@ttscoff
Created August 22, 2012 11:10
Show Gist options
  • Save ttscoff/3424487 to your computer and use it in GitHub Desktop.
Save ttscoff/3424487 to your computer and use it in GitHub Desktop.
Get first web search result as Markdown link
#!/usr/bin/ruby
require 'net/http'
def e_url(string)
string.gsub(/([^a-zA-Z0-9_.-]+)/n) do
'%' + $1.unpack('H2' * $1.size).join('%').upcase
end
end
def do_search(phrase)
res = Net::HTTP.get(URI.parse("http://duckduckgo.com/?q=%5C#{e_url(phrase)}"))
match = res.match(/window.location.replace\('(.*?)'\)/)
return match.nil? ? false : match[1]
end
ARGF.each do |input|
res = do_search(input.strip)
print %Q{[#{input.strip}](#{res.strip})}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment