how to grep one string occuring multiple times from same file

后端 未结 3 671
北荒
北荒 2021-01-29 14:24

I want to capture a string 1 row affected... But problem is there are no of such string present in the same file.

My concern to capture 1 row affecte

相关标签:
3条回答
  • 2021-01-29 14:49

    Assuming some input like

    $ printf "1 row affected...\nsomeline\nsomeline\nJob completed successfully\nsomeline\nsomeline\n2 row affected...\n3 row affected...\n"
    1 row affected...
    someline
    someline
    Job completed successfully
    someline
    someline
    2 row affected...
    3 row affected...
    

    Let's say you only want the first row after "Job completed successfully" that contains "row affected". You can pipe it like so

    | sed -n -e '/Job completed successfully/,$p' | grep -m 1 "affected"
    

    e.g

    $ printf "1 row affected...\nsomeline\nsomeline\nJob completed successfully\nsomeline\nsomeline\n2 row affected...\n3 row affected...\n" | sed -n -e '/Job completed successfully/,$p' | grep -m 1 "row affected"
    2 row affected...
    

    Where the sed matches any line containing Job completed successfully and returns from that line to the end of the file and grep -m NUM shows only the first NUM matches of grep. Could probably do it with one sed thought that gets more messy. If grep -m NUM is unavailable, you can just pipe to head, e.g.

    | sed -n -e '/Job completed successfully/,$p' | grep "affected" | head -n 1
    
    0 讨论(0)
  • 2021-01-29 14:57

    If you have GNU grep, you can make use of its ability to display trailing context of matches:

    cmd... | grep -A 5 "Job completed successfully" | grep "1 row affected"
    

    The first grep will look for the string Job completed successfully, while also providing the five subsequent lines. It is in those lines that the other grep looks for 1 row affected, and prints the match.

    0 讨论(0)
  • 2021-01-29 15:06
    perl -e 'while (<>) { if (/job completed successfully/) { $flag=1; } elsif (/1 row affected/) { print; } else { $flag=0; } }'
    
    0 讨论(0)
提交回复
热议问题