Python equivalent to perl -pe?

Yes, you can use Python from the command line. python -c <stuff> will run <stuff> as Python code. Example:

python -c "import sys; print sys.path"

There isn’t a direct equivalent to the -p option for Perl (the automatic input/output line-by-line processing), but that’s mostly because Python doesn’t use the same concept of $_ and whatnot that Perl does – in Python, all input and output is done manually (via raw_input()/input(), and print/print()).

For your particular example:

cat results.txt | python -c "import re, sys; print ''.join(re.sub(r'.+(\d\.\d+)\.\n', r'\1 ', line) for line in sys.stdin)"

(Obviously somewhat more unwieldy. It’s probably better to just write the script to do it in actual Python.)

Leave a Comment