Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Extract ranges of lines based on values in the lines 1

Status
Not open for further replies.

FedoEx

Technical User
Oct 7, 2008
49
US
Sample input
Code:
1  y  10
2  y  11
3  y  10
4  n  12
5  n  22
6  y  12
7  y  12
8  n  33
9  y  12
10 y  10
11 y  10
12 y  10
13 y  10
14 y  11

If I want to extract list of lines for which $2==y I can do.
Code:
awk '$2=="y"{print $1}'  list 
1
2
3
6
7
9
10
11
12
13
14
What I really need is to print the consecutive lines with the same third column value on the same line.
So the desired output is.
Code:
1
2
3 
6 7 
9
10 11 12 13
14
Alternative output that would suit me even better is
Code:
1
2
3 
6 - 7 
9
10 - 13
14
Any suggestions? Probably there is some special awk function that can compare values for the current record with the previous.
Thanks.
 
Hi

For the first output this should be enough :
Code:
awk '$2=="y"{printf "%s%s",l==$3?" ":"\n",$1}{l=$3}' /input/file
Tested with [tt]gawk[/tt] and [tt]mawk[/tt].

For the second output format, would be better to know more about the input :
[ul]
[li]Are $1 values strictly ascending ?[/li]
[li]Are $1 values continuous ?[/li]
[/ul]


Feherke.
 
Hi

If the answers for the above questions are yes, then try this :
Code:
awk '$2=="y"{if(l!=$3){print(n>1?" - "p:"");n=0};if(++n==1)printf"%s",$1;else p=$1}{l=$3}' /input/file
Tested with [tt]gawk[/tt] and [tt]mawk[/tt].

Feherke.
 
Thanks feherke.
$1 values are ascending integers from 1 to 1000.
 
Consider the input file where the last $2==y entries are consecutive.
Code:
1  y  10
2  y  11
3  y  10
4  n  12
5  n  22
6  y  12
7  y  12
8  n  33
9  y  12
10 y  10
11 y  10
12 y  10
13 y  10
14 n  12
Now the output of the the second code will give
Code:
1
2
3
6 - 7
9
10
The last line is missing - 13
Is there an easy fix for that.
Thanks.
 
Hi

Oops. Indeed.
Code:
awk '$2=="y"{if(l!=$3){print(n>1?" - "p:"");n=0};if(++n==1)printf"%s",$1;else p=$1}{l=$3}[highlight]END{if(n>1)print" - "p}[/highlight]' /input/file

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top