Mark Mahan
Mark Mahan

Reputation: 41

grep to find a string, get the line before and after with no line numbers displayed

Recently I had a need to search for a particular string in a file and I needed to display the line before and the line after the match.

File

AAAA
BBBB                      
CCCC
DDDD

Using google I found the following solution utilizing grep.

grep -n1 BBBB File

Which outputs,

1-AAAA
2-BBBB
3-CCCC

So this does what I want except it displays the line numbers in the output.

Is there a way to suppress the line numbers?

Upvotes: 3

Views: 5474

Answers (2)

Barmar
Barmar

Reputation: 782407

Use this:

grep -C 1 BBBB input

grep has three options for showing context lines:

  -A NUM, --after-context=NUM
          Print NUM lines of trailing context after matching lines.  Places a line  containing  --  between  contiguous  groups  of
          matches.
  -B NUM, --before-context=NUM
          Print  NUM  lines  of  leading  context  before matching lines.  Places a line containing -- between contiguous groups of
          matches.
  -C NUM, --context=NUM
          Print NUM lines of output context.  Places a line containing -- between contiguous groups of matches.

Upvotes: 5

perreal
perreal

Reputation: 98108

Just remove the n

grep -1 BBBB input

also with sed

sed -n 'N;N;/\n.*BBBB.*\n/p' input

Upvotes: 2

Related Questions