Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
700 views
in Technique[技术] by (71.8m points)

awk - Collapse sequential numbers to ranges in bash

I am trying to collapse sequential numbers to ranges in bash. For example, if my input file is

1
2
3
4
15
16
17
18
22
23
45
46
47

I want the output as:

1 4
15 18
22 23
45 47

How can I do this with awk or sed in a single line command?

Thanks for any help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
$ awk 'NR==1{first=$1;last=$1;next} $1 == last+1 {last=$1;next} {print first,last;first=$1;last=first} END{print first,last}' file
1 4
15 18
22 23
45 47

Explanation

  • NR==1{first=$1;last=$1;next}

    On the first line, initialize the variables first and last and skip to next line.

  • $1 == last+1 {last=$1;next}

    If this line continues in the sequence from the last, update last and jump to the next line.

  • print first,last;first=$1;last=first

    If we get here, we have a break in the sequence. Print out the range for the last sequence and reinitialize the variables for a new sequence.

  • END{print first,last}

    After we get to the end of the file, print the final sequence.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...