Skip to content

Instantly share code, notes, and snippets.

@zokis
Created August 29, 2012 15:06
Show Gist options
  • Save zokis/3514007 to your computer and use it in GitHub Desktop.
Save zokis/3514007 to your computer and use it in GitHub Desktop.
grep
#!/usr/bin/env python
# ecoding: utf-8
import sys
ENCONTRADO = 0
NAO_ENCONTRADO = 1
ERRO = 2
def colore_linha(linha, palavra):
colorida = "\033[1;31m%s\033[0;0m" % palavra
return linha.replace(palavra, colorida)
def busca_arquivo(busca, arquivo):
a = open(arquivo)
n_linha = 1
for linha in a:
if busca in linha:
yield (n_linha, "%s" % colore_linha(linha.strip(), busca))
n_linha += 1
a.close()
def main(args):
retorno = NAO_ENCONTRADO
try:
busca = args[1]
except IndexError:
print >>sys.stderr, "Uso: grep [OPÇÃO]... PADRÃO [ARQUIVO]..."
return ERRO
arquivos = args[2:]
try:
for arquivo in arquivos:
for r in busca_arquivo(busca, arquivo):
print "\033[0;32m%s\033[1;33m: \033[1;33m[\033[0;32m%s\033[1;33m]\033[0;0m %s" % (arquivo, r[0], r[1])
retorno = ENCONTRADO
except IOError, ex:
print >>sys.stderr, "grep.py: %s: %s" % (ex.filename, ex.strerror)
retorno = ERRO
return retorno
args = sys.argv
ret = main(args)
sys.exit(ret)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment