For Programmers: Free Programming Magazines  


Home > Archive > AWK > October 2006 > match pattern but print previous line









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author match pattern but print previous line
Pad

2006-10-12, 6:57 pm

I am trying to match a pattern in a file and if it matches, i would
like to print the previous line.

eg.
item: 303
record: 34553
..
...

item: 304
record 34554
...
..

If I grep for a particular record say 34553, i would like to get its
item number say 303. I think gnu grep would do the trick but we don't
use here. Any help from experts?

thanks
pad

Janis Papanagnou

2006-10-12, 6:57 pm

Pad wrote:
> I am trying to match a pattern in a file and if it matches, i would
> like to print the previous line.
>
> eg.
> item: 303
> record: 34553
> ..
> ...
>
> item: 304
> record 34554
> ...
> ..
>
> If I grep for a particular record say 34553, i would like to get its
> item number say 303. I think gnu grep would do the trick but we don't
> use here. Any help from experts?
>
> thanks
> pad
>


awk -v r=34554 '/item:/ {s=$2} /record/ && $2==r {print s}'

Janis
Kenny McCormack

2006-10-12, 6:57 pm

In article <egenef$spi$1@online.de>,
Janis Papanagnou <Janis_Papanagnou@hotmail.com> wrote:
>Pad wrote:
>
>awk -v r=34554 '/item:/ {s=$2} /record/ && $2==r {print s}'
>
>Janis


More simply (speaking more to the general problem posed than the
specific instance):

/record/ { print ll }
{ ll = $0 }

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com