Knowledge Base

Preserving for the future: Shell scripts, AoC, and more

Convert input sets of numbers to numerical sequences

Introduction

I wrote a function for shell (basically bash) that makes it possible to convert a series of numbers such as "1,5-8,15" into a completely enumerated sequence, so 1 5 6 7 8 15. I needed this to facilitate passing parameters to another function, but with the ability to give arbitrarily-grouped sets of numbers. You can see my gist on github.

convert_to_seq() {
  printf "${@}" | xargs -n1 -d',' | tr '-' ' ' | awk 'NF == 2 { system("/bin/seq "$1" "$2); } NF != 2 { print $1; }' | xargs
}

convert_to_seq "$1"

Try it out for yourself! If you are looking for such a function, here you go.

Examples

Input: 1,5,8-10
Output: 1 5 8 9 10

Input: 500-510,37
Output: 500 501 502 503 504 505 506 507 508 509 510 37

Comments