Reputation: 625
Please help to print consecutive number ranges like [Start –End] ..,
Sample Input
10
11
12
13
14
17
30
31
Desired output
10-14
17-17
30-31
Thanks in advance
Upvotes: 0
Views: 325
Reputation: 113834
$ awk 'NR==1 {a=$1;b=$1;next} ($1 != b+1){print a,"-",b; a=$1} {b=$1} END{print a,"-",b}' numbers
10 - 14
17 - 17
30 - 31
The above has two variables a
and b
. a
is the first number in the range. b
is the last number in the range that has been seen so far.
In awk
, NR
is the line (record) number. The first part of the awk
program just initializes the a
and b
variables with from the first line: NR==1 {a=$1;b=$1;next}
The next section of the program, ($1 != b+1){print a,"-",b; a=$1}
, checks to see if a new range has started. If so the old range is printed and a
is updated.
Regardless of whether a new range has started or not, b
is updated to the value in the current line: {b=$1}
.
After the last line has been seen, the END
block is executed. It just prints out the last range.
Upvotes: 1