码迷,mamicode.com
首页 > 编程语言 > 详细

python re删除匹配行

时间:2017-02-21 19:39:21      阅读:1181      评论:0      收藏:0      [点我收藏+]

标签:python re

re.compile(strPattern[, flag]):
这个方法是Pattern类的工厂方法,用于将字符串形式的正则表达式编译为Pattern对象。
第二个参数flag是匹配模式,取值可以使用按位或运算符‘|‘表示同时生效,比如re.I | re.M。
另外,你也可以在regex字符串中指定模式,比如re.compile(‘pattern‘, re.I | re.M)与re.compile(‘(?im)pattern‘)是等价的。


xxx.com文件内容
$TTL 600 ; 1 day
@               IN SOA  ns1.xxxx.com. root.xxxx.com.(
                        1002766  ; Serial
                        3600            ; Refresh (1 hour)
                        900             ; Retry (15 minutes)
                        3600000         ; Expire (5 weeks 6 days 16 hours)
                        3600            ; Minimum (1 hour)
                        )
@       2D      IN      NS      ns1.xxxx.com.
@       2D      IN      NS      ns2.xxxx.com.
$ORIGIN int.jumei.com.
;;
                           IN MX 5  mxbiz1.qq.com.
                           IN MX 10 mxbiz2.qq.com.
                           IN TXT   "v=spf1 include:spf.mail.qq.com ~all"
auth                       IN MX 5  mail.pub.jumei.com.
auth                       IN TXT   "v=spf1 ip4:x.x.x.x/24 ip4:x.x.x.x/24 ~all"
stk                        IN CNAME office.reemake.net.
signontest                 IN CNAME xxx.xxxx.com.
qqmaile33f7f2c             IN CNAME mail.qq.com.
*.kbs                      IN A     192.168.20.222
flow  IN  A  192.168.49.10
maven  IN  A  192.168.49.9
auth     IN      A       192.168.49.11
auth     IN      A       192.168.49.12
lynx-auth      IN      A   192.168.49.13
lynx-auth      IN      A   192.168.49.14



vim dns.py
#!/usr/bin/env python
import sys
import re

if __name__ == ‘__main__‘:
    content = []
    with open(‘xxx.com‘,‘r‘) as f:
        with open(‘xxx.com.bak‘, ‘w‘) as g:
            #读取原文件行
            for content in f.readlines():
                #把执行脚本的第一个参数赋予变量x
                x = sys.argv[1].strip()
                #匹配拼接以x变量 + 多空格 IN 多空格 A 开头的行 
                #其中 r‘‘ 是对引号中的字符串,保留字面,不进行转义
                p = re.compile(r‘^‘+x+r‘\s.+IN\s.+A‘)
                #p = re.compile(r‘^‘+x+r‘\w*\s.+IN\s.+A‘)
                #最后使用Match实例获得信息,如果不匹配re条件,写把行写到bak文件
                if not p.match(content):
                        g.write(content)
	    o = sys.argv[1].strip()
	    v = sys.argv[2].strip()
	    q = sys.argv[3].strip()
	    g.write("%s\tIN\tA\t%s\n" % (o,v))
	    g.write("%s\tIN\tA\t%s\n" % (o,q))
# ./dns.py auth 192.168.6.69 192.168.6.80
# diff xxx.com xxxx.com.bak
636,637d635
< auth 	 IN 	 A 	 x.x.x.x
< auth 	 IN 	 A 	 x.x.x.x
801a800,801
> auth	IN	A	192.168.6.69
> auth	IN	A	192.168.6.80


本文出自 “xieping_linux” 博客,请务必保留此出处http://xieping.blog.51cto.com/3715452/1899918

python re删除匹配行

标签:python re

原文地址:http://xieping.blog.51cto.com/3715452/1899918

(1)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!