评估bash中数字范围的重叠 [英] Evaluating overlap of number ranges in bash

查看:48
本文介绍了评估bash中数字范围的重叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设一个文本文件 file 包含多行数字范围.每个范围的下限和上限用短划线分隔,并对各个范围进行排序(即范围 101-297 排在 1299-1314 之前).

Assume a text file file which contains multiple lines of number ranges. The lower and upper bound of each range are separated by a dash, and the individual ranges are sorted (i.e., range 101-297 comes before 1299-1314).

$cat file
101-297
1299-1314
1301-5266
6898-14503

如何在 bash 中确认这些数字范围中的一个或多个是否重叠?

How can I confirm in bash if one or more of these number ranges are overlapping?

在我看来,所有需要的似乎是在相邻行之间迭代执行整数比较.单个整数比较可能如下所示:

In my opinion, all that is needed seems to be to iteratively perform integer comparisons across adjacent lines. The individual integer comparisons could look like something like this:

if [ "$upperbound_range1" -gt "$lowerbound_range2" ]; then
    echo "Overlap!"
    exit 1
fi

不过,我怀疑这种比较也可以通过 awk 完成.

I suspect, however, that this comparison can also be done via awk.

注意: 理想情况下,代码不仅可以确定是否有任何范围与其直接后继范围重叠,还可以确定哪个范围是重叠的.

Note: Ideally, the code could not only determine if any of the ranges is overlapping with its immediate successor range, but also which range is the overlapping one.

推荐答案

试试 awk.

awk -F"-" 'Q>=$1 && Q{print}{Q=$NF}'   Input_file

在此处设置 -(dash) 作为字段分隔符,然后检查名为 Q 的变量是否为 NOT NULL 并且其值是否大于当前行的第一个字段 ($1) 为 yes 然后打印该行(如果您想打印前一行我们也可以这样做),现在创建/重新分配变量 Q 的值到当前行的最后一个字段的值.

Making here -(dash) as a field separator then checking if a variable named Q is NOT NULL and it's value is greater then current line's first field($1) is yes then print that line(if you want to print previous line we could do that also), now create/re-assign variable Q's value to current line's last field's value.

根据 OP 用户想要获取上一行,因此现在也将其更改为该行.

As per OP user wants to get the previous line so changing it to that now too.

awk -F"-" 'Q>=$1 && Q{print val}{Q=$NF;val=$0}'  Input_file

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

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