1

I want to print the head of a file up to a match and some lines after the match.

I know that you can use sed '/PATTERN/q' FILE to print the file until the pattern. And sed 10q FILE top print the first 10 lines.


Starting with this file:

lorem
ipsum
dolor
sit
amet
consectetur
adipiscing
elit

If my pattern is dolor and I want 2 more lines the output will be:

lorem
ipsum
dolor
sit
amet

Is this a way to merge this two commands ?


Alos, is is possible to do the same for the end of the file (ie to print the tail of the file with some lines before the match) ?

If I keep the first file with the pattern amet and the 2 lines before the match, the output will be:

dolor
sit
amet
consectetur
adipiscing
elit

source: https://unix.stackexchange.com/a/11306/117394

jmlemetayer
  • 4,774
  • 1
  • 32
  • 46
  • 1
    Possible duplicate of [How to combine multiple sed commands into one](https://stackoverflow.com/questions/39130560/how-to-combine-multiple-sed-commands-into-one) – Inian Mar 30 '18 at 13:00
  • [edit] your question to include concise, testable sample input and expected output so we can help you come up with the best solution to your problem. – Ed Morton Mar 30 '18 at 13:06
  • Could you show a testable example for this – Inian Mar 30 '18 at 13:06
  • @Inian I have edited my question to add an example of what I want. – jmlemetayer Mar 30 '18 at 13:11

3 Answers3

1
$ awk '1; /dolor/{c=3} c&&(!--c){exit}' file
lorem
ipsum
dolor
sit
amet

$ tac file | awk '1; /amet/{c=3} c&&(!--c){exit}' | tac
dolor
sit
amet
consectetur
adipiscing
elit

See https://stackoverflow.com/a/17914105/1745001 for how to find lines around a regexp match with awk.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
0

Found a solution with awk:

awk '
{
    if (matched == 0) {
        print;
    } else if (lines > 0) {
        lines--;
        print;
    }
}

/dolor/ {
    matched = 1;
    lines = 2;
}' test

Inspired by: https://stackoverflow.com/a/5316718/2893600

jmlemetayer
  • 4,774
  • 1
  • 32
  • 46
0

With gnu sed

2 more lines after the pattern

sed '/^dolor/!b;N;N;q' infile

2 more lines before the pattern

sed 'N;:A;N;/\namet/!{s/[^\n]*\n//;bA };:B;N;bB' infile
ctac_
  • 2,413
  • 2
  • 7
  • 17