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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With