Friday, 15 April 2011

Manipulating stdin and redirect to stdout in Python -



Manipulating stdin and redirect to stdout in Python -

i'm trying write simple python script where

it takes values stdin replaces specific matched word passes on output new value stdout

i have part takes values stdin , looks matching words, i'm bit stuck after that.

import re import sys line in sys.stdin: matchobj = re.search(r'<something>(.*)</something>',line) if matchobj: oldword = matchobj.group(1) print oldword

contents of foo

<something>replaceme</something> <blah>untouch</blah>

ideally if run command

cat foo | ./test.py

i this

<something>newword</something <blah>untouch</blah>

are looking re.sub?

import re import sys line in sys.stdin: sys.stdout.write(re.sub(r'(<something>)replaceme(</something>)', r'\1newword\2', line))

running above on illustration data:

$ echo '<something>replaceme</something>\n<something>untouch</something>' | python2 test.py <something>newword</something> <blah>untouch</blah>

note parsing xml regular expressions bad idea. python standard library comes number of xml modules.

here's example:

import sys import xml.etree.elementtree tree = xml.etree.elementtree.parse(sys.stdin) root = tree.getroot() node in root.iter('something'): if node.text == 'replaceme': node.text == 'newword' tree.write(sys.stdout)

the above work same:

$ echo '<root><something>replaceme</something>\n<blah>untouch</blah></root>' | python2 test.py <root><something>replaceme</something> <blah>untouch</blah></root>

python python-2.7

No comments:

Post a Comment