ChrizZly
ChrizZly

Reputation: 124

Output only the first pattern-line and its following line

I need to filter the output of a command. I tried this.

bpeek | grep nPDE

My problem is that I need all matches of nPDE and the line after the found file. So the output would be like:

iteration nPDE
1         1
iteration nPDE
2         4

The best case would be if it would show me the found line only once and then only the line after it.

I found solutions with awk, But as far as I know awk can only read files.

Upvotes: 0

Views: 73

Answers (3)

Benjamin W.
Benjamin W.

Reputation: 52506

grep -A works if your grep supports it (it's not in POSIX grep). If it doesn't, you can use sed:

bpeek | sed '/nPDE/!d;N'

which does the following:

/nPDE/!d # If the line doesn't match "nPDE", delete it (starts new cycle)
N        # Else, append next line and print them both

Notice that this would fail to print the right output for this file

nPDE
nPDE
context line

If you have GNU sed, you can use an address range as follows:

sed '/nPDE/,+1!d'

Addresses of the format addr1,+N define the range between addr1 (in our case /nPDE/) and the following N lines. This solution is easier to adapt to a different number of context lines, but still fails with the example above.

A solution that manages cases like

blah
nPDE
context
blah
blah
nPDE
nPDE
context
nPDE

would like like

sed -n '/nPDE/{$p;:a;N;/\n[^\n]*nPDE[^\n]*$/!{p;b};ba}'

doing the following:

/nPDE/ {                       # If the line matches "nPDE"
    $p                         # If we're on the last line, just print it
    :a                         # Label to jump to
    N                          # Append next line to pattern space
    /\n[^\n]*nPDE[^\n]*$/! {   # If appended line does not contain "nPDE"
        p                      # Print pattern space
        b                      # Branch to end (start new loop)
    }
    ba                         # Branch to label (appended line contained "nPDE")
}

All other lines are not printed because of the -n option.

As pointed out in Ed's comment, this is neither readable nor easily extended to a larger amount of context lines, but works correctly for one context line.

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 204558

With awk (for completeness since you have grep and sed solutions):

awk '/nPDE/{c=2} c&&c--'

Upvotes: 1

Erki Aring
Erki Aring

Reputation: 2106

There is an option for that.

grep --help
...
  -A, --after-context=NUM   print NUM lines of trailing context

Therefore:

bpeek | grep -A 1 'nPDE'

Upvotes: 2

Related Questions