Grep为一个单词,如果找到的话打印10行之前和10行之后的模式匹配

2024-04-24 15:17:26 发布

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

我正在处理一个大文件。我想在一行中搜索一个单词,当找到时,我应该在模式匹配之前和之后打印10行。我如何用Python实现它?在


Tags: 文件单词
3条回答

试试这个

#!/usr/bin/python
import commands

filename = "any filename"
string_to_search = "What you want to search"

extract  = (commands.getstatusoutput("grep -C 10 '%s' %s"%(string_to_search,filename)))[1]

print(extract)
import collections
import itertools
import sys

with open('huge-file') as f:
    before = collections.deque(maxlen=10)
    for line in f:
        if 'word' in line:
            sys.stdout.writelines(before)
            sys.stdout.write(line)
            sys.stdout.writelines(itertools.islice(f, 10))
            break
        before.append(line)

使用^{}在匹配之前最多保存10行,使用^{}在匹配后获取下10行。在


更新排除ip/mac地址的线路:

^{pr2}$

使用grep-C选项,最简单的解决方案:

grep -C 10 'what_to_search' file.txt

相关问题 更多 >