Created
August 27, 2015 11:47
-
-
Save Achifaifa/3baa1a19d529dca1b71b to your computer and use it in GitHub Desktop.
Searches in a file/directory for a string. use with ./search.py <term> <file>. File types to be searched can be specified in the extensions variables. Using this with ./ as a path does weird stuff.
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
#! /usr/bin/env python | |
""" | |
Searches for a string inside text files | |
use: search.py <term> <file> | |
""" | |
import os, sys | |
def process(name,term): | |
""" | |
Processes a given file | |
""" | |
with open(name,"r") as filein: | |
lines=filein.readlines() | |
for line in lines: | |
if term in line: | |
print "="*80+"\nHit! in %s, line %i\n"%(name,lines.index(line)+1) | |
for i in range(-2,3): | |
print str(lines.index(line)+1+i)+" | "+lines[lines.index(line)+i].rstrip() | |
print "\n" | |
if __name__=="__main__": | |
extensions="py txt md".split() | |
term=sys.argv[1] | |
location=sys.argv[2] | |
if os.path.isdir(location): | |
files=os.walk(location) | |
for i in files: | |
for j in i[2]: | |
if j.split('.')[-1] in extensions: | |
process("%s/%s/%s"%(os.getcwd(),i[0],j),term) | |
elif os.path.isfile(location): | |
process(location,term) | |
else: | |
print "Not a valid location" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment