Shaddi
Shaddi

Reputation: 313

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?

Upvotes: 10

Views: 3167

Answers (4)

Bunyk
Bunyk

Reputation: 8067

There is even better way than sed, called pyp. Works like this:

pip install pyp
echo "apple, banana" | pyp "p.replace('apple', 'orange')"

Upvotes: 4

salezica
salezica

Reputation: 76889

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\"),"

Upvotes: 10

bash-o-logist
bash-o-logist

Reputation: 6911

If you are using the Bash shell

while read -r line
do
  line=${line//apple/orange/}
  echo "$line" 
done < file > tempfile && mv tempfile file

Upvotes: -1

user2665694
user2665694

Reputation:

Read your data from sys.stdin or just use 'sed'.

Upvotes: 0

Related Questions