Advertisement
rockdrilla

rolling/unrolling ranges in list, rev.0

Oct 18th, 2013
283
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 0.94 KB | None | 0 0
  1. params_or_stdin() { [ $# -eq 0 ] && cat || echo "$@"; }
  2.  
  3. list_unroll_int() {
  4.   tr -s ',' '\n' \
  5.   | tr -s '-' ' ' \
  6.   | while read -a L; do
  7.     [ ${#L[@]} -eq 1 ] && echo ${L[@]} && continue
  8.     echo ${L[@]} | xargs -rn2 seq
  9.   done \
  10.   | sort -n \
  11.   | paste -sd ',' -
  12. }
  13. list_unroll() { params_or_stdin "$@" | list_unroll_int; }
  14.  
  15. list_roll_int2() {
  16.   local a b c d
  17.   while read c; do
  18.     [ -z "$a" ] && { a=$c; b=$c; }
  19.     d=$[c-b]
  20.     if [ $d -lt 2 ]; then
  21.       [ $d -eq 1 ] && b=$c
  22.       continue
  23.     fi
  24.     [ $[b-a] -gt 0 ] && echo "$a-$b" || echo "$a"
  25.     a=$c; b=$c
  26.   done
  27.   [ $[b-a] -gt 0 ] && echo "$a-$b" || echo "$a"
  28. }
  29. list_roll_int() {
  30.   tr -s ',' ' ' \
  31.   | tr -s '[:space:]' '\n' \
  32.   | uniq -u \
  33.   | sort -n \
  34.   | list_roll_int2 \
  35.   | paste -sd ',' -
  36. }
  37. list_roll() { params_or_stdin "$@" | list_roll_int; }
  38.  
  39. list_unroll 1-5,13,9
  40. #output: 1,2,3,4,5,9,13
  41.  
  42. list_roll 1 2 3 4 6 10 8 14 11
  43. #output: 1-4,6,8,10-11,14
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement