How to use grep in IPython?

I installed PythonXY. How to use or install grepor grepas a function in IPython? This gives an error that is grepnot defined. I want to search for text in text files in a directory.

+4
source share
2 answers

Only with python code (> = 2.5):

import fileinput
import re
import glob

def grep(PAT, FILES):
    for line in fileinput.input(glob.glob(FILES)):
        if re.search(PAT, line):
            print fileinput.filename(), fileinput.lineno(), line

Then you can use it as follows:

grep('text', 'path/to/files/*')
+2
source

Assuming you are on a * nix system you can do:

File: file_1.txt

this is line one
this is line two
this is line three

the code:

import os
import subprocess

os.system('grep one file_1.txt')
subprocess.call(['grep', 'one', 'file_1.txt'])

The conclusion in both cases:

this is line one
+1
source

Source: https://habr.com/ru/post/1535870/


All Articles