折叠序号到bash中的范围 [英] Collapse sequential numbers to ranges in bash
问题描述
我正在尝试将连续数字折叠到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
我希望输出为:
1 4
15 18
22 23
45 47
如何用awk或sed在单行命令中执行此操作?
How can I do this with awk or sed in a single line command?
感谢您的帮助!
推荐答案
$ 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
说明
-
NR==1{first=$1;last=$1;next}
在第一行上,初始化变量first
和last
,然后跳到下一行.
On the first line, initialize the variables first
and last
and skip to next line.
$1 == last+1 {last=$1;next}
如果此行从上一行开始继续执行,请更新last
并跳至下一行.
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.
这篇关于折叠序号到bash中的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!