1

How do I Search string from command output and print next two lines from the output.

Below is code:

a = """
Some lines I do not want 
----- -------- --
I need this line
I need this line also
Again few lines i do not want
"""
for line in a.split("\n"):
    if line.startswith("----"):
        print "I need this line"
        print "I need this line also"

What I am doing in above code is I am checking if line starts with "----" and This works fine. Now How do i print exactly two lines after line starts with "----". In this example code print, " I need this line and I need this line also"

5 Answers 5

3

you can create an iterator out of the list (no need with a file handle BTW). Then let for iterate, but allow to use next manually within the loop:

a = """
Some lines I do not want
----- -------- --
I need this line
I need this line also
Again few lines i do not want
"""
my_iter = iter(a.splitlines())
for line in my_iter:
    if line.startswith("----"):
        print(next(my_iter))
        print(next(my_iter))

This code will raise StopIteration if there aren't enough lines after the dashes. One alternative that avoids this issue is (courtesy Jon Clements)

from itertools import islice

my_iter = iter(a.splitlines(True))  # preserves \n (like file handle would do)
for line in my_iter:
    if line.startswith("----"):
        print(''.join(islice(my_iter, 2)))

Another way, without splitting the string:

print(re.search("-----.*\n(.*\n.*)",a).group(1))

this searches for 2 lines after the pattern in the unsplitted, multi-line string. Can crash if re.search returns None because there are no more lines.

In both cases you get:

I need this line
I need this line also
Sign up to request clarification or add additional context in comments.

4 Comments

Or print ''.join(islice(my_iter, 2)) which scales a bit better if you want more than 2 lines and won't raise a StopIteration...
'\n'.join(islice(my_iter, 2)) then. nice. Long time no hear, always fan of your code.
Changed from '\n' to '' as if it's coming from a file (or your example string) - you don't want additional new lines between lines (as they'll end with '\n' anyway... (or most likely will)
Ahhh... didn't see the splitlines... could just change it to a.splitlines(True) and then you get the same as though it was a file :)
0

This is one simple way:

a = """
Some lines I do not want 
----- -------- --
I need this line
I need this line also
Again few lines i do not want
"""

lines = a.split("\n")
for i in range(len(lines)):
    if lines[i].startswith("----"):  # if current line starts with ----
        print(lines[i+1])  # print next line.
        print(lines[i+2])  # print line following next line.

# I need this line
# I need this line also                                      

Comments

0

You can store the index of the current line and thus get the next n lines:

a = """
Some lines I do not want 
----- -------- --
I need this line
I need this line also
Again few lines i do not want
"""
lines = a.split("\n")
for index, line in enumerate(lines):
    if line.startswith("----"):
        print lines[index+1]
        print lines[index+2]

You may want to check for IndexErrors though.

Comments

0

Plain way (almost C):

>>> a = """
Some lines I do not want
----- -------- --
I need this line
I need this line also
Again few lines i do not want
No nee
---- ------- --
Need this
And this
But Not this
"""

>>> start_printing, lines_printed = False, 0
>>> for line in a.split('\n'):
        if line.startswith('----'):
            start_printing = True
        elif start_printing:
            print line
            lines_printed += 1
        if lines_printed>=2:
            start_printing=False
            lines_printed = 0


I need this line
I need this line also
Need this
And this

Comments

0

Here something with list comprehensions:

    a = """
    Some lines I do not want 
    ----- -------- --
    I need this line
    I need this line also
    -----------------------
    A line after (---)
    A consecutive line after (---)
    """

   lines = a.split("\n")
   test = [print(lines[index+1] + '\n' + lines[index+2]) for index in range(len(lines)) if lines[index].startswith("----")]

 #Output:I need this line
         #I need this line also
         #A line after (---)
         #A consecutive line after (---)

I bumped into IndexError on further testing with more sentences, so I added an exception block:

a = """
Some lines I do not want 
----- -------- --
I need this line
I need this line also
-----------------------
A line after (---)
A consecutive line after (---)
-------------------------
Just for fun
Another one
-------------------------
"""
lines = a.split("\n")
try:
    test = [print(lines[index+1] + '\n' + lines[index+2]) for index in range(len(lines)) if lines[index].startswith("----")]
except:
    pass

Now, the desired output without exceptions:

I need this line
I need this line also
A line after (---)
A consecutive line after (---)
Just for fun
Another one

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.