|
|
#1 |
|
Prospect
Join Date: Sep 2009
Posts: 10
|
awk: how call field values from different lines
Hi,
I have a sample file that looks as follows: ext 25 / ext 36 | ext 43 / ext 87 | ext 95 / ext 234 / ext 345 | ext 500 / ext 536 | . . My desired output is to print on one line: field 1, field 2 from first line, field 2 from the second line, and the difference between lines of field 2 (see below). Note that when / is not followed by | I need to signal this with a zero length in the fourth field of the output. type start stop length ext 25 36 11 ext 43 87 44 ext 95 95 0 ext 234 345 111 ext 500 536 36 I've been fumbling with awk but my problem is to call the field values from different line records. Thanks for any suggestions. Best, K |
|
|
|
|
|
#2 |
|
All Star
Join Date: May 2007
Posts: 654
|
Something like this?
Code:
#! /bin/awk -f
BEGIN{
count=1
print "type start stop length"
}
{
if($NF ~ /\// ) {
name[count] = $1
val1[count] = $2
count++
flg = 1
}
if($NF ~ /\|/ && flg = 1) {
val2[count-1] = $2
}
}
END{
for(i=1;i<count;i++)
if(length(val2[i]) == 0)
print name[i],val1[i],val1[i],0
else
print name[i],val1[i],val2[i],val2[i]-val1[i]
}
Brett |
|
|
|
|
|
#3 |
|
Prospect
Join Date: Sep 2009
Posts: 10
|
That really did help - thanks a lot!
What I don't understand is the assignment of flg = 1 in the first if statement or the logical AND flg = 1 in the second if statement? What does this do? Maybe there is no time to answer stuff like that, but thanks again for the help! Best, K |
|
|
|
|
|
#4 |
|
MVP
Join Date: May 2004
Posts: 2,012
|
I think 'flg' is ensuring that a "first" line has been seen before processing a "second" line.
It's protecting against something like: ext 25 / ext 36 | ext 46 | ext 43 / ext 87 | Though, I'd think there'd need to be something like: Code:
if($NF ~ /\|/ && flg = 1) {
val2[count-1] = $2
flg = 0
}
|
|
|
|
|
|
#5 |
|
All Star
Join Date: May 2007
Posts: 654
|
You actually don't need "flg"
Originally I was trying to keep a status on the lines, but it turned out to be easier to do it the way it is. Of course it isn't very flexible. It only checks for two / characters, not two | characters. But it does give one an idea on how to check multiple lines. Also, as all the data is being stored in arrays, there is probably a size limit as it doesn't really operate on a Line by Line processing, at least the output doesn't. Brett |
|
|
|
|
|
#6 |
|
Prospect
Join Date: Sep 2009
Posts: 10
|
Thank you for your answers.
/K |
|
|
|
![]() |
| Thread Tools | |
| Display Modes | Rate This Thread |
|
|