如何通过Python运行unix命令来编辑文件

时间:2014-01-23 23:05:33

标签: python file unix subprocess in-place

我必须打开一个xml文件,修剪空格(除了换行符),删除所有与正则表达式匹配的行,然后删除与另一个正则表达式匹配的所有行。现在这是使用3个单独的临时文件,我知道这是不必要的。

# Trim whitespace from xml
f2 = open(fname + '.xml','r')
f3 = open(fname + 'temp.xml', 'w')
subprocess.call(["tr", "-d", "'\t\r\f'"], stdin=f2, stdout=f3)
f2.flush()
f3.flush()

# Remove the page numbers from the file                         
f4 = open(fname + 'temp2.xml', 'w')
subprocess.call(["sed",
"/<attr key=\"phc.line_number\"><integer>[0-9]*<\/integer><\/attr>/d",
                                    fname + 'temp.xml'], stdout=f4)
f4.flush()

# Remove references to filename from the file
--not implemented--

我有办法用一个文件完成所有这些吗?

1 个答案:

答案 0 :(得分:1)

$ sed -i -e 's/[ \r\t\f]//g' -e /pattern1/d -e /pattern2/d x.xml

注意多个-e参数。 -i将结果保留在x.xml