grep

New Programmer

A utility like the Linux/Unix grep command

3 bonuses 11 hints 63 solved 5 reviews

I'd like you to recreate a version of the grep Linux/Unix command-line program. This program might be handy if you're running Python on a machine that doesn't have grep (like an older version of Windows).

I'd like you to start by making a program which accepts 2 or more positional command-line arguments and one optional command-line flag.

Given this file, dickinson.txt:

I'm Nobody! Who are you?
Are you – Nobody – too?
Then there's a pair of us!
Don't tell! they'd advertise – you know!

How dreary – to be – Somebody!
How public – like a Frog –
To tell one's name – the livelong June –
To an admiring Bog!

By Emily Dickinson (1891)

And this file, scrambled.txt:

I'm Frog! Who are you?
Are you – Somebody – too?
Then there's a pair of us!
Don't tell! they'd tell – you know!

How public – to be – Nobody!
How livelong – like a name –
To advertise one's Bog – the dreary June –
To an admiring Nobody!

By Eminick Dilyson (1981)

The grep.py program should work like this:

$ python grep.py to dickinson.txt
Are you – Nobody – too?
How dreary – to be – Somebody!
$ python grep.py Nobody dickinson.txt scrambled.txt
dickinson.txt:I'm Nobody! Who are you?
dickinson.txt:Are you – Nobody – too?
scrambled.txt:How public – to be – Nobody!
scrambled.txt:To an admiring Nobody!

The first argument is the string that's being looked for and all arguments after that are the files that will be searched. If more than one file is given, the filename is shown before each matched line.

Your grep.py program also needs to support an optional -i or --ignore-case argument:

$ python grep.py Are dickinson.txt -i
I'm Nobody! Who are you?
Are you – Nobody – too?
$ python grep.py --ignore-case FROG dickinson.txt scrambled.txt
dickinson.txt:How public – like a Frog –
scrambled.txt:I'm Frog! Who are you?

Your grep.py program should process the given files line-by-line instead of reading the files in-full.

If you finish the base problem, try one or more of the bonuses. You'll need to solve them in order.

Bonus 1


Trey Hunner

Want to solve this one?

Hi, I’m Trey, and I teach Python. Give this one a go, then I’ll show you how I’d solve it.

Sign up and solve it 7 days of All Access, no card needed