Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, pipes, and the "-c" option in the command line

I vaguely recall being able to do something like this in Python:

cat foo | python -c "<some python code>" | grep blah | ... 

For some reason I'm blanking on how to actually use this to run Python code on each line of the input file. For instance, say I wanted to change every instance of the word "apple" in the original file to "orange"; how would I do that?

like image 640
Shaddi Avatar asked Apr 21 '11 03:04

Shaddi


1 Answers

I don't see how this can be helpful more than once, but here's a one-liner:

cat file | grep apple | python -c "for line in __import__('sys').stdin: print line.replace(\"apple\", \"orange\"),"
like image 195
slezica Avatar answered Oct 28 '22 17:10

slezica