sdbbs
sdbbs

Reputation: 5470

Prepend match number to output match lines of grep?

Say I have this file, test.log:

blabla test test
20 30 40
hello world
100 100
34 506 795
blabla test2
50 60 70
hello
10 10
200 200
blabla test BB
30 40 50
100 100
20 20 20 20

I would like to print all lines with blabla in them, the line after that - with the match number prepended.

Without match number, it is easy:

$ grep -A1 "blabla" test.log
blabla test test
20 30 40
--
blabla test2
50 60 70
--
blabla test BB
30 40 50

With a prepended match number, it would look like this:

1: blabla test test
1: 20 30 40
--
2: blabla test2
2: 50 60 70
--
3: blabla test BB
3: 30 40 50

The tricky part is, I want to preserve the match number, regardless if I just grep for a single line match, or with context (X lines after or before the match).

Is there an easy way to do this? If I could do a format specifier for the number, as in %03d, even better - but just a usual number would be fine too...

Upvotes: 1

Views: 86

Answers (2)

choroba
choroba

Reputation: 241988

Perl to the rescue!

perl -ne '/blabla/ and print ++$i, ":$_" and print "$i:", scalar <>' -- file
  • -n reads the input line by line
  • each line is read into the special variable $_
  • the diamond operator <> reads the next line from the input file
  • scalar makes it read just one line, not all the remaining ones
  • the variable $i is incremented each time blabla is encountered and is prepended to each output line.

Your specification doesn't handle the case when two blablas are present on adjacent lines.

To format the numbers, use sprintf:

perl -ne 'if (/blabla/) { $f = sprintf "%03d", ++$i; print $f, ":$_"; print "$f:", scalar <>}'

Upvotes: 1

Shawn
Shawn

Reputation: 52529

Something like

 grep -A1 blahblah test.log | awk -v n=1 '$0 == "--" { n += 1; print; next }
                                          { printf("%03d: %s\n", n, $0) }'

Upvotes: 1

Related Questions