Created
November 13, 2012 09:44
-
-
Save dansimau/4064926 to your computer and use it in GitHub Desktop.
Recursive grep-like search for extracting URLs from a bunch of files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import re | |
import sys | |
# Crazy URL regexp from Gruber | |
# http://daringfireball.net/2010/07/improved_regex_for_matching_urls | |
r = re.compile(r'(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?]))') | |
# grep -r | |
for parent, dnames, fnames in os.walk(sys.argv[1]): | |
for fname in fnames: | |
filename = os.path.join(parent, fname) | |
if os.path.isfile(filename): | |
with open(filename) as f: | |
c = 0 | |
for line in f: | |
c = c + 1 | |
match = r.search(line) | |
if match: | |
# <file>:<line>:<match> | |
print '%s:%s:%s' % (filename, c, match.string[match.start():match.end()]) | |
# <match> | |
#print match.string[match.start():match.end()] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example rev 2: