Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use grep in IPython?

I have installed PythonXY. How do I use or install grep or a grep like function in IPython? It gives an error that grep is not defined. I want to search for text in text files in a directory.

like image 460
user3518093 Avatar asked Apr 10 '14 06:04

user3518093


People also ask

Can you use grep in Python?

You're probably familiar with the grep command if you're a Linux user. You can create your command using Python programming to search for a string pattern in the specified files. The application also allows you to search for patterns utilizing regular expressions.

How do I run IPython commands?

If you want some code to be run at the beginning of every IPython session, the easiest way is to add Python (. py) or IPython (. ipy) scripts to your profile_default/startup/ directory. Files here will be executed as soon as the IPython shell is constructed, before any other code or scripts you have specified.

What is %% capture in Python?

Capturing Output With %%capture IPython has a cell magic, %%capture , which captures the stdout/stderr of a cell. With this magic you can discard these streams or store them in a variable.

What is IPython command?

IPython bridges this gap, and gives you a syntax for executing shell commands directly from within the IPython terminal. The magic happens with the exclamation point: anything appearing after ! on a line will be executed not by the Python kernel, but by the system command-line.


1 Answers

With just python (>=2.5) code:

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 this way:

grep('text', 'path/to/files/*')
like image 79
Claudio Avatar answered Sep 29 '22 00:09

Claudio