In Bash, how to convert number list into ranges of numbers?

点点圈 提交于 2019-11-30 20:34:19

Yes, shell does variable substitution, if prev is not set, that line becomes:

if [ -ne $n+1] 

Here is a working version:

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

With a function:

#!/bin/bash

list2range() {
  set -- ${@//,/ }       # convert string to parameters

  local first a b string IFS
  local -a array
  local endofrange=0

  while [[ $# -ge 1 ]]; do  
    a=$1; shift; b=$1

    if [[ $a+1 -eq $b ]]; then
      if [[ $endofrange -eq 0 ]]; then
        first=$a
        endofrange=1
      fi
    else
      if [[ $endofrange -eq 1 ]]; then
        array+=($first-$a)
      else
        array+=($a)
      fi
      endofrange=0
    fi
  done

  IFS=","; echo "${array[*]}"
}

list2range 18,19,62,161,162,163,165

Output:

18-19,62,161-163,165
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!