查找两个变量是否在同一个lin中

2024-04-19 22:40:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个IP列表。我想验证每一对都存在于文件的同一行:ips_template.txt。如果文件ips_template.txt中不存在IP或它们不是“对”,则打印不匹配的IP。在bash中,我只需要通过管道传输两个grep,寻找具有相同结果的东西。你知道吗

firstIPs = re.findall(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", firststring)
secondIPs = re.findall(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", secondstring)

if firstIPs or secondIPs :
    print 'one of the lists didn\'t had IPs.'
    sys.exit(2)
if len(firstIPs ) != len(secondIPs ):
    print 'IPs len mismatch'
    sys.exit(2)

for old, new in zip(firstIPs , secondIPs ):
# bash example to search in the file ips_template.txt
# if [ `cat ips_template.txt | grep old | grep new | wc -l` -gt 0 ]
#    echo 'match'
# else
#    echo ips not matched or missing
# fi

ips_template.txtexmaple公司:

hostname 1.1.1.1 2.2.2.2 hostname_type
hostname2 1.1.1.1 2.2.2.2 hostname_type2

firststringsecondstring可以是不同的格式,有些是未知的。这就是为什么我只从这些IP中剥离IP,并假设IP/主机的顺序是相同的。你知道吗


Tags: 文件ipretxtbashleniftemplate
1条回答
网友
1楼 · 发布于 2024-04-19 22:40:30

要在ips_template.txt中搜索IP,我执行了以下操作:

with open("ips_template.txt", "r") as ips_template_file:
    ips_template = ips_template_file.readlines()

for old, new in zip(firstIPs , secondIPs ):
    missing = True
    pattern = r"%s\s*%s" % (old, new)

    for line in ips_template:
        if re.search(pattern, line):
            print("matched %s %s" % (old, new))
            missing = False
            break

    if missing:
        print("missing %s %s" % (old, new))

另外,在检查列表中是否包含IP时,我插入了两个not

if not firstIPs or not secondIPs:

因为它只说“其中一个列表没有IP”,而其中至少有一个包含IP


我的完整代码是:

import re
import sys

firststring = "1.1.1.1\n1.1.1.1\n3.3.3.3\n2.2.2.2"
secondstring = "1.1.1.1\n2.2.2.2\n not an IP adress\n2.2.2.2\n4.4.4.4"

firstIPs = re.findall(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", firststring)
secondIPs = re.findall(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", secondstring)

if not firstIPs or not secondIPs :
    print('one of the lists didn\'t had IPs.')
    sys.exit(2)
if len(firstIPs ) != len(secondIPs ):
    print('IPs len mismatch')
    sys.exit(2)

with open("ips_template.txt", "r") as ips_template_file:
    ips_template = ips_template_file.readlines()

for old, new in zip(firstIPs , secondIPs ):
    missing = True
    pattern = r"%s\s*%s" % (old, new)

    for line in ips_template:
        if re.search(pattern, line):
            print("matched %s %s" % (old, new))
            missing = False
            break

    if missing:
        print("missing %s %s" % (old, new))

ips_template.txt看起来像这样:

hostname 1.1.1.1    1.1.1.1 hostname_type
hostname2 3.3.3.3  2.2.2.2 hostname_type2
hostname3 2.2.2.2 2.2.2.2 hostname_type3

我的代码输出是:

matched 1.1.1.1 1.1.1.1
missing 1.1.1.1 2.2.2.2
matched 3.3.3.3 2.2.2.2
missing 2.2.2.2 4.4.4.4

相关问题 更多 >