如何在Python中匹配后获取所有行

时间:2016-10-11 18:00:10

标签: python

我是Python的新手,我在这里看了一篇文章: How to grab the lines AFTER a matched line in python

我有一个包含以下格式数据的文件:     DEFINE JOBPARM ID =(ns_ppprtg_notify,nj_pprtd028_notify,0028)

SUBFILE='/sybods/prod/ca_scripts/ca_notify.ksh' SUBUSER=pbods SUBPASS=*PASSWORD*

我正在尝试提取每个参数,以便我可以构造完整的命令行。

这是我到目前为止所做的:

with open(myExtract) as Extract:
    for line in Extract:

        currentLine = line.strip("\n").strip()

        if currentLine.startswith("DEFINE JOBPARM ID=") or \
                currentLine.contains("PARM")):

            logger.info("Job Parameter line found")

            if "DEFINE JOBPARM ID=" in currentLine:
                tJobParmString = currentLine.partition("DEFINE JOBPARM ID=")[2].parition("SUBFILE")[0].strip()
                tSubFileString = currentLine.partition("SUBFILE")[2].partition("SUBUSER")[0].strip()
                tSubUserString = currentLine.partition("SUBUSER")[2].partition("SUBPASS")[0].strip()

                if re.match(" PARM", currentLine, flags=0):
                    logger.info("PARM line found")

这是我被困的地方...... 我不确定会有2条PARM线或10条。它们都以" PARM"并有数字。如何提取PARM1,PARM2,PARM3等的值? 每个PARM行(PARM1,PARM2)始终以新行开始。

任何指针都会受到赞赏。

2 个答案:

答案 0 :(得分:1)

if("DEFINE JOBPARM ID=" in currentLine):
                tJobParmString=currentLine.partition("DEFINE JOBPARM ID=")[2].partition("SUBFILE")[0].strip()
                tSubFileString=currentLine.partition("SUBFILE")[2].partition("SUBUSER")[0].strip()
                tSubUserString=currentLine.partition("SUBUSER")[2].partition("SUBPASS")[0].strip()
            if(re.match("PARM",currentLine,flags=0)):
                logger.info("PARM line found")
                tParmString=currentLine.partition("=")[2].strip()
                logger.info(tParmString)
                if(not "PARM" in currentLine):
                    continue

答案 1 :(得分:0)

你在这里交配。这是我对你的问题的尝试。我在数据结构布局中给了你三个选项;将PARM映射到字符串的outDict; outListOfTups,它为您提供与元组列表相同的数据;和假设你对PARMS不感兴趣的outList

f = open("data.txt", 'r')
lines = f.read().splitlines()
outDict = {}
outListOfTups = []
outList = []

for line in lines:
    if line.startswith('PARM'):
        splitPoint = line.find("'")
        name = line[:splitPoint-1]
        string = line[splitPoint:].replace("'", "")
        outDict[name] = string #if you want to work with dict
        outListOfTups.append((name, string)) #if you want lists
        outList.append(string)

print(outDict)
print(outList)
print(outListOfTups)

如果我误解了你的来源,请告诉我 - 这对我提供的输入样本很有用。