1

I know how to use grep -B n -A m match to print n and m lines before and after a match. I also know how to use sed to print from match1 until match2. But how can I combine these in a one-liner:

> cat file.txt

    bar
    foo
    bar
    baz
    match1
    qux
    blah
    bleep
    match2
    boop
    blah

Sample Output for n=2:

    bar
    baz
    match1
    qux
    blah
    bleep
    match2
1

Group the commands, that way they share the same input, so when grep quits sed takes over:

{ grep -B2 -m1 match1; sed '/match2/q'; } < infile
0

Try piping the output of the grep command to the sed command? E.g.,

grep <options> file | sed <options>
0

sed is a stream editor. so if you want print previous lines that is already gone you need to keep them in buffer for later use. so i first keep two lines in the buffer 1{N;N} and maintained with N;D commands

sed -rn '1{:X N;N}; 
/match1[^\n]*$/{:Y N; /match2[^\n]*$/{p;n;bX}; bY};
N;D' infile

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.