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

Python 如何在文本文件的行中查找子字符串并打印特定行,python,python-2.7,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] 我需要使用python打印包含“开始”的行…作为命令行的一行: 代码: pytho

我有这样一个文件:

[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]

我需要使用python打印包含“开始”的行…

作为命令行的一行:

代码:

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]

在第行中使用条件表达式
'START',其中
是要检查的行。

您可以使用
re

见演示

假设您有一个包含数据的file.txt文件 您可以使用以下代码
Happing coding

斯蒂芬·劳赫(Stephen Rauch)给出的答案很酷,但我认为您是python新手,因此这里有一个基本函数

考虑到“开始”必须始终位于消息的开头,而不是介于两者之间

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

如果我们考虑上面的用例,这里是一个函数,它可以在日志消息开始时打印文件中存在的“代码>开始”<代码>。

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.

输出:


为什么在
中使用
\uuuuuuu包含
而不是
[739:247021] PHYThrad: START DSPMsgQ  Received: msg type is[130] and SFNSF [14997] [SFN:937 SF:5] # START at second index after split.
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]