How to fetch 3 lines above a matched parameter

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
0
down vote

favorite
1












I want to print 3 lines above a matched parameter in a log file. I am using following command, but it gives me an error.
Is there any alternative to this.




grep -A 3 "exception" Services.log




It gives the following error:



grep: Not a recognized flag: A
Usage: grep [-r] [-R] [-H] [-L] [-E|-F] [-c|-l|-q] [-insvxbhwyu] [-p[parasep]] -e pattern_list...
[-f pattern_file...] [file...]






share|improve this question

















  • 1




    I've added the aix tag to your question. Let us know if you're on some other Unix than AIX.
    – Kusalananda
    yesterday







  • 1




    Yes im on Aix, Sorry i forgot to mention
    – Hamas Rizwan
    yesterday










  • could you clarify whether you want 3 lines that occur before the matching line or you want 3 lines that occur after the matching line? for example, if you have 10 lines in input and matching line is 5th, you want 5,6,7,8 or 2,3,4,5?
    – Sundeep
    yesterday
















up vote
0
down vote

favorite
1












I want to print 3 lines above a matched parameter in a log file. I am using following command, but it gives me an error.
Is there any alternative to this.




grep -A 3 "exception" Services.log




It gives the following error:



grep: Not a recognized flag: A
Usage: grep [-r] [-R] [-H] [-L] [-E|-F] [-c|-l|-q] [-insvxbhwyu] [-p[parasep]] -e pattern_list...
[-f pattern_file...] [file...]






share|improve this question

















  • 1




    I've added the aix tag to your question. Let us know if you're on some other Unix than AIX.
    – Kusalananda
    yesterday







  • 1




    Yes im on Aix, Sorry i forgot to mention
    – Hamas Rizwan
    yesterday










  • could you clarify whether you want 3 lines that occur before the matching line or you want 3 lines that occur after the matching line? for example, if you have 10 lines in input and matching line is 5th, you want 5,6,7,8 or 2,3,4,5?
    – Sundeep
    yesterday












up vote
0
down vote

favorite
1









up vote
0
down vote

favorite
1






1





I want to print 3 lines above a matched parameter in a log file. I am using following command, but it gives me an error.
Is there any alternative to this.




grep -A 3 "exception" Services.log




It gives the following error:



grep: Not a recognized flag: A
Usage: grep [-r] [-R] [-H] [-L] [-E|-F] [-c|-l|-q] [-insvxbhwyu] [-p[parasep]] -e pattern_list...
[-f pattern_file...] [file...]






share|improve this question













I want to print 3 lines above a matched parameter in a log file. I am using following command, but it gives me an error.
Is there any alternative to this.




grep -A 3 "exception" Services.log




It gives the following error:



grep: Not a recognized flag: A
Usage: grep [-r] [-R] [-H] [-L] [-E|-F] [-c|-l|-q] [-insvxbhwyu] [-p[parasep]] -e pattern_list...
[-f pattern_file...] [file...]








share|improve this question












share|improve this question




share|improve this question








edited yesterday









Jeff Schaller

30.7k846104




30.7k846104









asked yesterday









Hamas Rizwan

334




334







  • 1




    I've added the aix tag to your question. Let us know if you're on some other Unix than AIX.
    – Kusalananda
    yesterday







  • 1




    Yes im on Aix, Sorry i forgot to mention
    – Hamas Rizwan
    yesterday










  • could you clarify whether you want 3 lines that occur before the matching line or you want 3 lines that occur after the matching line? for example, if you have 10 lines in input and matching line is 5th, you want 5,6,7,8 or 2,3,4,5?
    – Sundeep
    yesterday












  • 1




    I've added the aix tag to your question. Let us know if you're on some other Unix than AIX.
    – Kusalananda
    yesterday







  • 1




    Yes im on Aix, Sorry i forgot to mention
    – Hamas Rizwan
    yesterday










  • could you clarify whether you want 3 lines that occur before the matching line or you want 3 lines that occur after the matching line? for example, if you have 10 lines in input and matching line is 5th, you want 5,6,7,8 or 2,3,4,5?
    – Sundeep
    yesterday







1




1




I've added the aix tag to your question. Let us know if you're on some other Unix than AIX.
– Kusalananda
yesterday





I've added the aix tag to your question. Let us know if you're on some other Unix than AIX.
– Kusalananda
yesterday





1




1




Yes im on Aix, Sorry i forgot to mention
– Hamas Rizwan
yesterday




Yes im on Aix, Sorry i forgot to mention
– Hamas Rizwan
yesterday












could you clarify whether you want 3 lines that occur before the matching line or you want 3 lines that occur after the matching line? for example, if you have 10 lines in input and matching line is 5th, you want 5,6,7,8 or 2,3,4,5?
– Sundeep
yesterday




could you clarify whether you want 3 lines that occur before the matching line or you want 3 lines that occur after the matching line? for example, if you have 10 lines in input and matching line is 5th, you want 5,6,7,8 or 2,3,4,5?
– Sundeep
yesterday










2 Answers
2






active

oldest

votes

















up vote
2
down vote













The following awk command would give you the line that contains the string exception along with three lines of "before context" (-B 3 with GNU grep and some other grep implementations):



awk 'BEGIN bc=3 lines[NR%(bc+1)] = $0 /exception/ for (i=1; i<=(bc+1); ++i) print lines[(NR+i)%(bc+1)] ' file


This keeps a "circular buffer", lines, of bc+1 lines, where bc is the number of lines of "before context" you want. When a line matches the pattern exception, the contents of this buffer is printed.



This does not properly handle the case where a match occurs within the "before context" of another match, or where the first match in the file occurs less than bc lines into the file.



Generalized into a script that gives you a configurable amount of context before and after for some pattern:



#!/bin/sh

# Usage:
# ./script [ -A n ] [ -B n ] PATTERN FILE ...

after=0
before=0

while getopts 'A:B:' opt; do
case $opt in
A)
after=$OPTARG
;;
B)
before=$OPTARG
;;
*)
echo 'error in command line parsing' >&2
exit 1
esac
done
shift "$(( OPTIND - 1 ))"

pattern=$1
shift

pattern=$pattern awk -v bc="$before" -v ac="$after" '
lines[NR%(bc+1)] = $0
$0 ~ ENVIRON["pattern"]
for (i=1; i<=(bc+1); ++i) print lines[(NR+i)%(bc+1)]
print_after=ac
next

print_after > 0 print; print_after-- ' "$@"


Testing it:



$ cat file
1
2
3
4
5
exception
6
7
8
9
0
exception




$ sh script.sh -B 3 exception file
3
4
5
exception
8
9
0
exception




$ sh script.sh -A 3 exception file
exception
6
7
8
exception




$ sh script.sh -A 1 -B 1 exception file
5
exception
6
0
exception





share|improve this answer




























    up vote
    0
    down vote













    Simple but not necessarily efficient:



    tac Services.log | awk '/exception/ L = NR + 4 NR < L' | tac





    share|improve this answer

















    • 1




      If they don't have GNU grep, then the are unlikely to have other GNU utilities, such as tac (part of GNU coreutils).
      – Kusalananda
      yesterday










    Your Answer







    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "106"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: false,
    noModals: false,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );








     

    draft saved


    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f460624%2fhow-to-fetch-3-lines-above-a-matched-parameter%23new-answer', 'question_page');

    );

    Post as a guest






























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    2
    down vote













    The following awk command would give you the line that contains the string exception along with three lines of "before context" (-B 3 with GNU grep and some other grep implementations):



    awk 'BEGIN bc=3 lines[NR%(bc+1)] = $0 /exception/ for (i=1; i<=(bc+1); ++i) print lines[(NR+i)%(bc+1)] ' file


    This keeps a "circular buffer", lines, of bc+1 lines, where bc is the number of lines of "before context" you want. When a line matches the pattern exception, the contents of this buffer is printed.



    This does not properly handle the case where a match occurs within the "before context" of another match, or where the first match in the file occurs less than bc lines into the file.



    Generalized into a script that gives you a configurable amount of context before and after for some pattern:



    #!/bin/sh

    # Usage:
    # ./script [ -A n ] [ -B n ] PATTERN FILE ...

    after=0
    before=0

    while getopts 'A:B:' opt; do
    case $opt in
    A)
    after=$OPTARG
    ;;
    B)
    before=$OPTARG
    ;;
    *)
    echo 'error in command line parsing' >&2
    exit 1
    esac
    done
    shift "$(( OPTIND - 1 ))"

    pattern=$1
    shift

    pattern=$pattern awk -v bc="$before" -v ac="$after" '
    lines[NR%(bc+1)] = $0
    $0 ~ ENVIRON["pattern"]
    for (i=1; i<=(bc+1); ++i) print lines[(NR+i)%(bc+1)]
    print_after=ac
    next

    print_after > 0 print; print_after-- ' "$@"


    Testing it:



    $ cat file
    1
    2
    3
    4
    5
    exception
    6
    7
    8
    9
    0
    exception




    $ sh script.sh -B 3 exception file
    3
    4
    5
    exception
    8
    9
    0
    exception




    $ sh script.sh -A 3 exception file
    exception
    6
    7
    8
    exception




    $ sh script.sh -A 1 -B 1 exception file
    5
    exception
    6
    0
    exception





    share|improve this answer

























      up vote
      2
      down vote













      The following awk command would give you the line that contains the string exception along with three lines of "before context" (-B 3 with GNU grep and some other grep implementations):



      awk 'BEGIN bc=3 lines[NR%(bc+1)] = $0 /exception/ for (i=1; i<=(bc+1); ++i) print lines[(NR+i)%(bc+1)] ' file


      This keeps a "circular buffer", lines, of bc+1 lines, where bc is the number of lines of "before context" you want. When a line matches the pattern exception, the contents of this buffer is printed.



      This does not properly handle the case where a match occurs within the "before context" of another match, or where the first match in the file occurs less than bc lines into the file.



      Generalized into a script that gives you a configurable amount of context before and after for some pattern:



      #!/bin/sh

      # Usage:
      # ./script [ -A n ] [ -B n ] PATTERN FILE ...

      after=0
      before=0

      while getopts 'A:B:' opt; do
      case $opt in
      A)
      after=$OPTARG
      ;;
      B)
      before=$OPTARG
      ;;
      *)
      echo 'error in command line parsing' >&2
      exit 1
      esac
      done
      shift "$(( OPTIND - 1 ))"

      pattern=$1
      shift

      pattern=$pattern awk -v bc="$before" -v ac="$after" '
      lines[NR%(bc+1)] = $0
      $0 ~ ENVIRON["pattern"]
      for (i=1; i<=(bc+1); ++i) print lines[(NR+i)%(bc+1)]
      print_after=ac
      next

      print_after > 0 print; print_after-- ' "$@"


      Testing it:



      $ cat file
      1
      2
      3
      4
      5
      exception
      6
      7
      8
      9
      0
      exception




      $ sh script.sh -B 3 exception file
      3
      4
      5
      exception
      8
      9
      0
      exception




      $ sh script.sh -A 3 exception file
      exception
      6
      7
      8
      exception




      $ sh script.sh -A 1 -B 1 exception file
      5
      exception
      6
      0
      exception





      share|improve this answer























        up vote
        2
        down vote










        up vote
        2
        down vote









        The following awk command would give you the line that contains the string exception along with three lines of "before context" (-B 3 with GNU grep and some other grep implementations):



        awk 'BEGIN bc=3 lines[NR%(bc+1)] = $0 /exception/ for (i=1; i<=(bc+1); ++i) print lines[(NR+i)%(bc+1)] ' file


        This keeps a "circular buffer", lines, of bc+1 lines, where bc is the number of lines of "before context" you want. When a line matches the pattern exception, the contents of this buffer is printed.



        This does not properly handle the case where a match occurs within the "before context" of another match, or where the first match in the file occurs less than bc lines into the file.



        Generalized into a script that gives you a configurable amount of context before and after for some pattern:



        #!/bin/sh

        # Usage:
        # ./script [ -A n ] [ -B n ] PATTERN FILE ...

        after=0
        before=0

        while getopts 'A:B:' opt; do
        case $opt in
        A)
        after=$OPTARG
        ;;
        B)
        before=$OPTARG
        ;;
        *)
        echo 'error in command line parsing' >&2
        exit 1
        esac
        done
        shift "$(( OPTIND - 1 ))"

        pattern=$1
        shift

        pattern=$pattern awk -v bc="$before" -v ac="$after" '
        lines[NR%(bc+1)] = $0
        $0 ~ ENVIRON["pattern"]
        for (i=1; i<=(bc+1); ++i) print lines[(NR+i)%(bc+1)]
        print_after=ac
        next

        print_after > 0 print; print_after-- ' "$@"


        Testing it:



        $ cat file
        1
        2
        3
        4
        5
        exception
        6
        7
        8
        9
        0
        exception




        $ sh script.sh -B 3 exception file
        3
        4
        5
        exception
        8
        9
        0
        exception




        $ sh script.sh -A 3 exception file
        exception
        6
        7
        8
        exception




        $ sh script.sh -A 1 -B 1 exception file
        5
        exception
        6
        0
        exception





        share|improve this answer













        The following awk command would give you the line that contains the string exception along with three lines of "before context" (-B 3 with GNU grep and some other grep implementations):



        awk 'BEGIN bc=3 lines[NR%(bc+1)] = $0 /exception/ for (i=1; i<=(bc+1); ++i) print lines[(NR+i)%(bc+1)] ' file


        This keeps a "circular buffer", lines, of bc+1 lines, where bc is the number of lines of "before context" you want. When a line matches the pattern exception, the contents of this buffer is printed.



        This does not properly handle the case where a match occurs within the "before context" of another match, or where the first match in the file occurs less than bc lines into the file.



        Generalized into a script that gives you a configurable amount of context before and after for some pattern:



        #!/bin/sh

        # Usage:
        # ./script [ -A n ] [ -B n ] PATTERN FILE ...

        after=0
        before=0

        while getopts 'A:B:' opt; do
        case $opt in
        A)
        after=$OPTARG
        ;;
        B)
        before=$OPTARG
        ;;
        *)
        echo 'error in command line parsing' >&2
        exit 1
        esac
        done
        shift "$(( OPTIND - 1 ))"

        pattern=$1
        shift

        pattern=$pattern awk -v bc="$before" -v ac="$after" '
        lines[NR%(bc+1)] = $0
        $0 ~ ENVIRON["pattern"]
        for (i=1; i<=(bc+1); ++i) print lines[(NR+i)%(bc+1)]
        print_after=ac
        next

        print_after > 0 print; print_after-- ' "$@"


        Testing it:



        $ cat file
        1
        2
        3
        4
        5
        exception
        6
        7
        8
        9
        0
        exception




        $ sh script.sh -B 3 exception file
        3
        4
        5
        exception
        8
        9
        0
        exception




        $ sh script.sh -A 3 exception file
        exception
        6
        7
        8
        exception




        $ sh script.sh -A 1 -B 1 exception file
        5
        exception
        6
        0
        exception






        share|improve this answer













        share|improve this answer



        share|improve this answer











        answered yesterday









        Kusalananda

        100k13199311




        100k13199311






















            up vote
            0
            down vote













            Simple but not necessarily efficient:



            tac Services.log | awk '/exception/ L = NR + 4 NR < L' | tac





            share|improve this answer

















            • 1




              If they don't have GNU grep, then the are unlikely to have other GNU utilities, such as tac (part of GNU coreutils).
              – Kusalananda
              yesterday














            up vote
            0
            down vote













            Simple but not necessarily efficient:



            tac Services.log | awk '/exception/ L = NR + 4 NR < L' | tac





            share|improve this answer

















            • 1




              If they don't have GNU grep, then the are unlikely to have other GNU utilities, such as tac (part of GNU coreutils).
              – Kusalananda
              yesterday












            up vote
            0
            down vote










            up vote
            0
            down vote









            Simple but not necessarily efficient:



            tac Services.log | awk '/exception/ L = NR + 4 NR < L' | tac





            share|improve this answer













            Simple but not necessarily efficient:



            tac Services.log | awk '/exception/ L = NR + 4 NR < L' | tac






            share|improve this answer













            share|improve this answer



            share|improve this answer











            answered yesterday









            RudiC

            612




            612







            • 1




              If they don't have GNU grep, then the are unlikely to have other GNU utilities, such as tac (part of GNU coreutils).
              – Kusalananda
              yesterday












            • 1




              If they don't have GNU grep, then the are unlikely to have other GNU utilities, such as tac (part of GNU coreutils).
              – Kusalananda
              yesterday







            1




            1




            If they don't have GNU grep, then the are unlikely to have other GNU utilities, such as tac (part of GNU coreutils).
            – Kusalananda
            yesterday




            If they don't have GNU grep, then the are unlikely to have other GNU utilities, such as tac (part of GNU coreutils).
            – Kusalananda
            yesterday












             

            draft saved


            draft discarded


























             


            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f460624%2fhow-to-fetch-3-lines-above-a-matched-parameter%23new-answer', 'question_page');

            );

            Post as a guest













































































            Popular posts from this blog

            Peggy Mitchell

            The Forum (Inglewood, California)

            Palaiologos