how to grep one string occuring multiple times from same file

后端 未结 3 676
北荒
北荒 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
    

提交回复
热议问题