Raziel Raziel - 5 months ago 7
Bash Question

Generate ranges from entries in a file

I have a txt file containing entries as below

1
2
3
4
7
8
9
12
14
15


I need to generate ranges as below

1-4
7-9
12-12
14-15


How do I achieve the above output?

This is what I tried:

awk '{q=$1}{f=$1}{print $q} $1!=p+1{print l"-"f}{l=p+1}{p=$1} END{print}' filename

Answer

I would say...

awk -v OFS=- 'prev+1<$0 {print first ? first : 1,prev; first=$0}
              {prev=$0}
              END {print first, prev}' file

For your given file it returns:

$ awk -v OFS=- 'prev+1<$0 {print first ? first : 1,prev; first=$0} {prev=$0} END {print first, prev}' file
1-4
7-9
12-12
14-15
Comments