hauntsaninja / pyp

Easily run Python at the shell! Magical, but never mysterious.
MIT License
1.41k stars 39 forks source link

grep equivalence #32

Closed wangjiawen2013 closed 1 year ago

wangjiawen2013 commented 1 year ago

Hi, Very useful tool! What's the grep equivalence in pyp ? For example, how to achieve the function of 'grep "abcdef" -A 1 -B2 file.txt' using pyp ?

hauntsaninja commented 1 year ago

Hello! Glad you find it useful.

I don't think there's a particularly nice way to get grep's -A or -B behaviour. But you could do e.g.:

pyp 'idxs = [i for i, l in enumerate(lines) if "abc" in l]' '"\n--\n".join("\n".join(lines[idx-1:idx+2]) for idx in idxs)'

where -1 and +2 are your -B and -A` values respectively.

If you know you have exactly one match, you could do something slightly simpler:

pyp 'idx = next(i for i, l in enumerate(lines) if "abc" in l)' '"\n".join(lines[idx-1:idx+2])'

And of course, you could also write a function that does grep or import one from an existing package. pyp's automatic imports and config make this easy to do.

My intention with pyp isn't to fully replace specialised tools. Just rather — if you know Python and you don't know a specialised tool, you can use pyp to get something worknig without much pain :-)