Skip to content
Advertisement

Group the consecutive numbers in shell

JavaScript

In shell, how to group the numbers in $foo as 1-3,6-8,11,13-17

Advertisement

Answer

As an alternative, you can use this awk command:

JavaScript

Now run it as:

JavaScript

Here is an one-liner for doing the same:

JavaScript

In this awk command we keep 2 variables:

  1. p for storing previous line’s number
  2. s for storing start of the range that need to be printed

How it works:

  1. When NR==1 we set s to first line’s number
  2. When p is less than (current_number -1) or $1-1 that indicates we have a break in sequence and we need to print the range.
  3. We use a function prnt for doing the printing that accepts only one argument that is end delimiter. When prnt is called from p < $1-1 { ...} block then we pass RS or comma as end delimiter and when it gets called from END{...} block then we pass ORS or newline as delimiter.
  4. Inside p < $1-1 { ...} we reset s (start range) to $1
  5. After processing each line we store $1 in variable p.
  6. prnt uses printf for formatted output. It always prints starting number s first. Then it checks if p > s and prints hyphen followed by p if that is the case.
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement