在Bash中,如何将数字列表转换为数字范围? [英] In Bash, how to convert number list into ranges of numbers?
问题描述
目前,我从命令中获得了数字的排序输出:
Currently I have a sorted output of numbers from a command:
18,19,62,161,162,163,165
18,19,62,161,162,163,165
我想将这些数字列表压缩为单个数字或数字范围的列表
I would like to condense these number lists into a list of single numbers or ranges of numbers
18-19,62,161-163,165
18-19,62,161-163,165
我考虑过尝试对bash中的数组进行排序并读取下一个数字以查看其是否为+1 ...重击:
I thought about trying to sort through the array in bash and read the next number to see if it is +1... I have a PHP function that does essentially the same thing, but I'm having trouble transposing it to Bash:
foreach ($missing as $key => $tag) {
$next = $missing[$key+1];
if (!isset($first)) {
$first = $tag;
}
if($next != $tag + 1) {
if($first == $tag) {
echo '<tr><td>'.$tag.'</td></tr>';
} else {
echo '<tr><td>'.$first.'-'.$tag.'</td></tr>';
}
unset($first);
}
}
我在想bash中可能有一个衬里可以做到这一点,但我的Google搜寻工作即将结束....
I'm thinking there's probably a one-liner in bash that could do this but my Googling is coming up short....
更新: 谢谢@Karoly Horvath提供的快速答案,我曾经用它来完成我的项目.我肯定会对任何更简单的解决方案感兴趣.
UPDATE: Thank you @Karoly Horvath for a quick answer which I used to finish my project. I'd sure be interested in any simpler solutions out there.
推荐答案
是的,shell进行变量替换,如果未设置prev
,则该行变为:
Yes, shell does variable substitution, if prev
is not set, that line becomes:
if [ -ne $n+1]
这是一个有效的版本:
numbers="18,19,62,161,162,163,165"
echo $numbers, | sed "s/,/\n/g" | while read num; do
if [[ -z $first ]]; then
first=$num; last=$num; continue;
fi
if [[ num -ne $((last + 1)) ]]; then
if [[ first -eq last ]]; then echo $first; else echo $first-$last; fi
first=$num; last=$num
else
: $((last++))
fi
done | paste -sd ","
18-19,62,161-163,165
这篇关于在Bash中,如何将数字列表转换为数字范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!