Collapse sequential numbers to ranges in bash

随声附和 提交于 2019-12-18 05:16:06

问题


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!


回答1:


$ 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.



来源:https://stackoverflow.com/questions/26809668/collapse-sequential-numbers-to-ranges-in-bash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!