简体   繁体   English

检查并合并重叠范围

[英]Check for and combine overlapping ranges

How can I check if ranges overlap other ranges and combine the ones that do?我如何检查范围是否与其他范围重叠并将重叠的范围组合起来?

Example:例子:

10-1000,15-350,50-1500,2100,1700-1800,45,40,145,2-1300

The result I want is:我想要的结果是:

2-1500,1700-1800,2100

I tried to make a plan on how to code it but it's getting me nowhere.我试图制定一个关于如何编码的计划,但它让我无处可去。 Is there a useful package that I can use?我可以使用有用的 package 吗? Or if not what should my approach be?或者,如果不是,我的方法应该是什么?

Using sort and awk :使用sortawk

tr , '\n' | sort -n | awk '
BEGIN {
  FS = OFS = "-"
}
NF == 1 {
  $2 = $1
}
$2 <= end {
  next
}
$1 <= end {
  end = $2
  next
}
{
  emit()
  start = $1
  end = $2
}
END {
  emit()
}
function emit() {
  if (NR != 1) {
    if (start == end)
      print start
    else
      print start, end
  }
}' | paste -sd,
$ sh ./merge.sh <<<10-1000,15-350,50-1500,2100,1700-1800,45,40,145,2-1300
2-1500,1700-1800,2100

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM