Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Awk - print next record following matched record

Tags:

awk

I'm trying to get a next field after matching field using awk.

Is there an option to do that or do I need to scan the record into array then check each field in array and print the one after that?

What I have so far:

The file format is:

<FIELD><separator "1"><VALUE><separator "1"><FIELD><separator "1"><VALUE> 

... and so on, field|value pairs are repeated, will be at least one pair in line or multiple pairs <10 per line

dat.txt:

FIELDA01VALUEA01FIELDA21VALUEA21FIELDA31VALUEA3
FIELDB01VALUEB01FIELDB21VALUEB21FIELDB31VALUEB3
FIELDC01VALUEC01FIELDC21VALUEC21FIELDC31VALUEC3
FIELDD01VALUED01FIELDD21VALUED21FIELDD31VALUED3
FIELDE01VALUEE01FIELDE21VALUEE21FIELDE31VALUEE3

With simple awk script which prints the second field on a line matching FIELDB2:

#!/bin/awk -f

BEGIN { FS = "1" }
/FIELDB2/ { print $2 }

Running the above:

> ./scrpt.awk dat.txt

Gives me:

VALUEB0

This is because the line that match:

FIELDB01VALUEB01FIELDB21VALUEB21FIELDB31VALUEB3

When split into records looks:

FIELDB0 VALUEB0 FIELDB2 VALUEB2 FIELDB3 VALUEB3

From which the second field is VALUEB0

Now I don't know which FIELDXX will match but I would like to print the next record on the line after FIELDXX that matched, in this specific example when FIELDB2 matches I need to print VALUEB2.

Any suggestions?

like image 205
stefanB Avatar asked Nov 19 '09 06:11

stefanB


1 Answers

You can match the line, then loop over the fields for a match, and print the next record:

awk -F1 '/FIELDB2/ { for (x=1;x<=NF;x++) if ($x~"FIELDB2") print $(x+1) }' 
like image 175
Christopher Pickslay Avatar answered Sep 22 '22 17:09

Christopher Pickslay