python中的Sed命令



我的输入是

Type combinational  function (A B)

希望输出为

Type combinational 
function (A B)

我使用了代码及其工作

sed 's/([^ ]* [^ ]*) (function.*)/1n2/' Input_file

当我在使用os.systemsubprocess的python脚本中使用此代码时,会出现错误。如何在python脚本中执行这个sed。或者我如何为上面的sed code编写python代码。使用的Python代码

cmd='''
sed 's/([^ ]* [^ ]*) (function.*)/1n2/' Input_file
'''
subprocess.check_output(cmd, shell=True)

错误为

sed: -e expression #1, char 34: unterminated `s' command 

字符串中的n被Python替换为一个文本换行符。正如@bereal在评论中所建议的那样,您可以通过在脚本中使用r'''...'''而不是'''...'''来避免这种情况;但更好的解决方案是避免在sed中做Python本身已经做得很好的事情。

with open('Input_file') as inputfile:
lines = inputfile.read()
lines = lines.replace(' function', 'nfunction')

这比当前的sed脚本稍微不那么严格,因为它不需要在function标记之前正好有两个空格分隔的标记。如果你想严格一点,可以试试re.sub()

import re
# ...
lines = re.sub(r'^(S+s+S+)s+(function)', r'1n2', lines, re.M)

(切向而言,您还希望避免不必要的shell=True;也许可以参见子流程中';shell=True';的实际含义(

虽然解决方案1和2是让代码运行(在Unix上(的最短有效方法,但我想补充一些备注:

a。os.system()有一些与之相关的问题,应该用subprocess.call("your command line", shell=False)来代替。无论使用os.system还是subprocess.callshell=True都意味着安全风险。

b。由于sed(和awk(是严重依赖正则表达式的工具,因此在构建python以提高可维护性时,建议使用本机python代码。在这种情况下,使用re,正则表达式模块,该模块具有regexp优化的实现。

最新更新