如何在文本文件的行中查找子字符串并打印特定行

时间:2017-04-14 06:30:21

标签: python python-2.7

我有一个这样的文件:

[739:246050] START of MACThread:receved msg type[47]
[739:247021] PHYThrad: DSPMsgQ  Received: msg type is[130] and SFNSF [14997] [SFN:937 SF:5]
[739:247059] START of MACThread:receved msg type[47]

我需要打印包含" START"使用python ...

5 个答案:

答案 0 :(得分:2)

作为命令行中的一个班轮:

<强>代码:

python -c "import sys;[sys.stdout.write(l) for l in sys.stdin if ' START ' in l]" < file1

<强>结果:

[739:246050] START of MACThread:receved msg type[47]
[739:247059] START of MACThread:receved msg type[47]

答案 1 :(得分:1)

Stephen Rauch给出的答案很酷,但我认为你是python的新手,所以这是一个基本功能。

考虑到,“START”必须始终位于Message的开头,而不是像<,p>之间

[739:247021] PHYThrad: START DSPMsgQ  Received: msg type is[130] and SFNSF [14997] [SFN:937 SF:5] # START at second index after split.

如果我们考虑上面的用例,这里有一个函数可以在日志消息的开头打印文件中出现的"START"行。

def getStart(filename):
    with open(filename, "r") as reader:
        for lines in reader.readlines(): # get list of lines
            start =  lines.split(' ')[1] # Split with space, and check the word is "START"
            if start =='START':
                print lines

getStart("a.txt") # considering your filename is a.txt.
  

输出:

[739:246050] START of MACThread:receved msg type[47]

[739:247059] START of MACThread:receved msg type[47]

答案 2 :(得分:0)

您可以使用re

参见演示。

https://regex101.com/r/sLKG1U/3

import re

regex = r"^\[[^\]]*\]\s*(START\b.*)"

test_str = ("[739:246050] START of MACThread:receved msg type[47]\n"
"[739:247021] PHYThrad: DSPMsgQ  Received: msg type is[130] and SFNSF [14997] [SFN:937 SF:5]\n"
"[739:247059] START of MACThread:receved msg type[47]")

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches):
    matchNum = matchNum + 1

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end =     match.end(groupNum), group = match.group(groupNum)))

答案 3 :(得分:0)

$("body").on("blur",".bweight",function(){
    var text = $(this).val();
    alert(text);
 });

假设您有一个包含数据的file.txt 您可以使用以下代码 加强编码

答案 4 :(得分:-2)

使用条件表达式'START' in line,其中line是您要检查的行。