D. Tassie
D. Tassie

Reputation: 13

How to print the 'nth + x' lines after a match is found?

I have a file which contains the output below. I want only the lines which contain the actual vm_id number.

I want to match pattern 'vm_id' and print 2nd line + all other lines until 'rows' is reached.

FILE BEGIN:
                vm_id                 
--------------------------------------
 bf6c4f90-2e71-4253-a7f6-dbe5d666d3a4
 bf6c4f90-2e71-4253-a7f6-dbe5d666d3a4
 6ffac9a9-1b6b-4600-8114-1ca0666951be
 47b5e6d1-6ddd-424a-ab08-18ee35b54ebf
 cc0e8b36-eba3-4846-af08-67ab72d911fc
 1b8c2766-92b7-477a-bc92-797a8cb74271
 c37bf1d8-a6b2-4099-9d98-179b4e573c64
(6 rows)

datacenter=
FILE END:

So the resulting output would be;

 bf6c4f90-2e71-4253-a7f6-dbe5d666d3a4
 6ffac9a9-1b6b-4600-8114-1ca0666951be
 47b5e6d1-6ddd-424a-ab08-18ee35b54ebf
 cc0e8b36-eba3-4846-af08-67ab72d911fc
 1b8c2766-92b7-477a-bc92-797a8cb74271
 c37bf1d8-a6b2-4099-9d98-179b4e573c64

Also, the number of VM Id's will vary, this example has 6 while others could have 3 or 300.

I have tried the following but they only output a single line that's specified;

awk 'c&&!--c;/vm_id/{c=2}' 
and
awk 'c&&!--c;/vm_id/{c=2+1}' 

Upvotes: 1

Views: 823

Answers (2)

hek2mgl
hek2mgl

Reputation: 157947

What about this:

awk '/vm_id/{p=1;getline;next}/\([0-9]+ rows/{p=0}p' 

I'm setting the p flag on vm_id and resetting it on (0-9+ rows).

Also sed comes in mind, the command follows basically the same logic as the awk command above:

sed -n '/vm_id/{n;:a;n;/([0-9]* rows)/!{p;ba}}'

Another thing, if it is safe that the only GUIDs in your input file are the vm ids, grep might be the tool of choise:

grep -Eo '([0-9a-f]+-){4}([0-9a-f]+)'

It's not 100% bullet proof in this form, but it should be good enough for the most use cases.

Bullet proof would be:

grep -Eoi '[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}'

Upvotes: 1

Ed Morton
Ed Morton

Reputation: 203189

$ awk '/rows/{f=0} f&&(++c>2); /vm_id/{f=1}' file
 bf6c4f90-2e71-4253-a7f6-dbe5d666d3a4
 6ffac9a9-1b6b-4600-8114-1ca0666951be
 47b5e6d1-6ddd-424a-ab08-18ee35b54ebf
 cc0e8b36-eba3-4846-af08-67ab72d911fc
 1b8c2766-92b7-477a-bc92-797a8cb74271
 c37bf1d8-a6b2-4099-9d98-179b4e573c64

If you wanted that first line of hex(?) printed too then just change the starting number to compare c to from 2 to 1 (or 3 or 127 or however many lines you want to skip after hitting the vm_id line):

$ awk '/rows/{f=0} f&&(++c>1); /vm_id/{f=1}' file
 bf6c4f90-2e71-4253-a7f6-dbe5d666d3a4
 bf6c4f90-2e71-4253-a7f6-dbe5d666d3a4
 6ffac9a9-1b6b-4600-8114-1ca0666951be
 47b5e6d1-6ddd-424a-ab08-18ee35b54ebf
 cc0e8b36-eba3-4846-af08-67ab72d911fc
 1b8c2766-92b7-477a-bc92-797a8cb74271
 c37bf1d8-a6b2-4099-9d98-179b4e573c64

Upvotes: 2

Related Questions