search regex line by line and print multiple lines after match
Question: just started writing scripts.

I am trying to write 4 lines after matching a regex in the first line and do
this through a very large file with thousands of lines.

    
    
    #!/usr/local/bin/python
    import sys
    import string
    import re
    
    print"what file would you like to search?"
    filename = sys.stdin.readline()
    filename = filename.rstrip()
    print "enter a barcode"
    barcode=sys.stdin.readline()
    barcode=barcode.rstrip()
    regex=":0:"+barcode
    infile = open(filename, "r")
    outfile = open("sample_write.fastq", "w")
    regex_object = re.compile(regex, re.I)
    for line in infile:
       m=regex_object.search(line)
       if m:
          outfile.write(line)
    exit
    

This writes the lines that have matched string (barcode) into my outfile,
however, I need to write both the line with the barcode and the following 3
lines after the match into my target file. Any idea ?


Answer: You can use the following to match

    
    
    .*(BARCODE).*\n.*\n.*\n.*    //replace BARCODE with your variable
    

and write the matches (`\0`) to your target file

See [DEMO](https://regex101.com/r/tC0lJ0/4)

**Edit:** Use `regex =".*("+barcode+").*\n.*\n.*\n.*"`

