qbi
qbi

Reputation: 2144

Shell: searching for a pattern in a file and extracting a data block which contains the pattern

Given is a file with the following structure:

a 123
b 876234
c 56456
d 65765

a 9879
b 9361
c 6527
d 823468

So there are blocks of data (lines beginning with a,b,c,d and an empty line divides two blocks) and I'm looking for a pattern (e.g. 9361) inside this file. If this pattern is found inside I want to copy the whole block (line starting with a 9879 and ending with d 823468) and write it to another file.

This pattern can be found zero or more times inside a file. If there are more than one results each block should be written to the other file.

How would you do it?

Upvotes: 0

Views: 496

Answers (3)

kurumi
kurumi

Reputation: 25609

Ruby(1.8+)

ruby -00 -ne 'print if /9361/' file

Upvotes: 0

Zsolt Botykai
Zsolt Botykai

Reputation: 51663

You can do it with gawk.

gawk 'BEGIN {RS=""} /here goes your pattern/ { print $0}' INPUTFILE > OUTPUTFILE

This sets gawk's record separator to the empty line(s).

HTH

Upvotes: 3

heijp06
heijp06

Reputation: 11808

Assuming your data is in file.txt, this is a solution in perl.

perl -00 -ne "print if /9361/" file.txt

The result is on stdout.

  • -00 causes perl to read the file a paragraph at a time.
  • -n causes perl to read filename arguments one by one.
  • -e is to specify a perl command.

Upvotes: 2

Related Questions