Python使用正则表达式删除多个文件中的字符串(多行)

时间:2015-05-19 10:49:03

标签: python regex

我正在寻找一个删除某个字符串(多行)和多个文件的python脚本(文件数量未知,但它们都在同一个文件夹中)

假设此位置有2个文件:

'd:\测试\测试' 称为XML_1.xml和XML_2.xml(如果有更多文件,则数量会增加)

所有文件都遵循以下结构:

krb5.conf

应删除<action> some action another action another action again </action> <action> some action 2 another action 2 </action> <action> ... </action> 后跟<action>(空行也可以),因此输出应为:

</action>

我对python和regex都没有经验,类似的问题+答案对我来说似乎是中文

由于

2 个答案:

答案 0 :(得分:0)

sed是一个很好的工具

sed -i 's^</action>^^g' XML_*.xml

这将替换您工作日中与</action>正则表达式匹配的所有文件中的XML_*.xml

其中:

s = change
^ = separator
</action> = is the matching string
^^ = is a blank. if we want to replace a string with string it would be 's^</action>^newstring_here^g'
g = match multiple occasions

答案 1 :(得分:-1)

分多步拆分您的解决方案:

  1. 单独加载每个文件(例如在循环中),您可以使用glob来实现此目的
  2. 处理单个文件
  3. 然后,可以通过多个步骤拆分单个文件的处理:

    1. 应用正则表达式过滤(查找相关教程)。
    2. 使用新结果覆盖旧文件。