开发者

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

I vaguely r开发者_如何学运维ecall 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?


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


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

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


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


If you are using the Bash shell

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜