Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python as "perl -pe", execute Python command for every line in stdin [duplicate]

Tags:

python

sed

awk

perl

Possible Duplicate:
Python equivalent to perl -pe?

Is there a way to process each line of stdin with a given Python command without setting up things with boilerplate code?

With Perl, I can just do something like:

perl -pe '... command ...'

can I do the same with Python?

Note: something similar is possible with many other tools, e.g. sed, awk, etc...

like image 628
Robottinosino Avatar asked Sep 04 '12 08:09

Robottinosino


1 Answers

Python is not as convenient as Perl in this regard, but you can get close to Perl's -p flag using fileinput, like this:

python -c 'for ln in __import__("fileinput").input(): print ln.rstrip()' files...

This will automatically open files in sequence like Perl does, or use the standard input if no files are provided. Replace print with any kind of processing. You might need multiple lines to do anything useful, but that is not a problem for most shells.

Note that rstrip is needed to avoid duplication of newlines from the source lines and those added by the print statement. If you're not printing the line, you don't need to call it.

like image 91
user4815162342 Avatar answered Oct 18 '22 15:10

user4815162342