Python as "perl -pe", execute a Python command for each line in stdin

Possible duplicate:
Python equivalent for perl -pe?

Is there a way to handle every stdin line with a given Python command without setting up template files?

With Perl, I can just do something like:

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

Is it possible to do the same with Python?

Note: something similar is possible with many other tools, for example. sed, awk etc.

+4
source share
3 answers

In this regard, Python is not as convenient as Perl, but you can get closer to the Perl -p icon using fileinput , for example:

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

This will automatically open files in a sequence similar to Perl, or use standard input if files are not provided. Replace print with any kind of processing. You may need a few lines to do something useful, but this is not a problem for most shells.

Note that rstrip necessary to avoid duplicating newlines from the original lines and those added by the print statement. If you are not printing a line, you do not need to call it.

+5
source

Try the -c option of the interpreter:

 python -c "print 'cool'" 
-1
source

you can enter interactive mode from a regular bash shell by running the following command: python

-1
source

Source: https://habr.com/ru/post/1432218/


All Articles