简体   繁体   English

在python中匹配文本后打印第N行

[英]Print a Nth line after matching text in python

I am trying to print 13th line in a text file after the every search match. 我试图在每次搜索匹配后在文本文件中打印第13行。 Means everytime a searching pattern is found in text file, it should print the next 13th line from the searching text found. 意味着每次在文本文件中找到搜索模式时,都应该从找到的搜索文本中打印下一行第13行。

Code I am using now, prints only the current line where the search matches. 我现在使用的代码仅打印搜索匹配的当前行。 Can anybody help me how to print the 13th line after each match. 有人可以帮我在每次比赛后打印第13行吗?

import sys
import re
com=str(sys.argv[1])
with open("/tmp/sample.txt", 'r') as f:
    for line in f:
          if com in line:
            print (line)

The easiest way would be to read all lines at once, then search and print: 最简单的方法是一次读取所有行,然后搜索并打印:

import sys
import re
com=str(sys.argv[1])
with open("/tmp/sample.txt", 'r') as f:
    lines = f.readlines()
    for index, line in enumerate(lines):
        if com in line:
            print lines[index+13]

Supposing, of course, that there still is a line to print 13 lines down... Otherwise, your could add: 当然,假设还有一行可以向下打印13行...否则,您可以添加:

        ....
        if com in line:
            try:
                print lines[index+13]
            except IndexError:
                pass  # or whatever you want to do.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM