python sed not working
-
08-07-2021 - |
Question
Why is it so hard to do sed like operation in Python?
cat temp$$ | sed '/ENTRY/d' | sed '/VERSION/d' > temp$$1
The following attempt simply doesn't work (instead of writing to file I'm printing to screen):
70 for line in open("temp5027", 'r'):
71
72 if re.search("ENTRY|VERSION", line) != None:
73 pass
74 else:
75 print line
A frustrated first time python user.
Note: I'm using python 2.4 so no "with" support yet.
Solution
Write to file with Python 2.4
import re
i = open("in.txt")
o = open("out.txt", "w")
for line in i:
if re.search("ENTRY|VERSION", line):
o.write(line)
o.close()
i.close()
Write to file with modern Python
import re
with open("in.txt") as i, open("out.txt", "w") as o:
for line in i:
if re.search("ENTRY|VERSION", line):
o.write(line)
Bonus
Improve your sed
usage.
$ sed -e '/ENTRY/d' -e '/VERSION/d' < in.txt > out.txt
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow