将序列号折叠到bash中的范围 [英] Collapse sequential numbers to ranges in bash

查看:19
本文介绍了将序列号折叠到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}

在第一行,初始化变量 firstlast 并跳到下一行.

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.

打印 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{打印第一个,最后一个}

到达文件末尾后,打印最终序列.

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

这篇关于将序列号折叠到bash中的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆