Mike
Mike

Reputation: 13

pbsnodes and bash string matching

I have a string of the form: "8, 14-24, 30-45, 9", which is a substring of the output of pbsnodes. This shows the cores in use on a given node, where 14-24 is a range of cores in use.

I'd like to know the total number of cores in use from this string, i.e. 1 + (24 - 14 + 1) + (45 - 30 + 1 )+ 1 in this example, using a bash script.

Any suggestions or help is much appreciated.

Michael

Upvotes: 1

Views: 82

Answers (1)

Inian
Inian

Reputation: 85845

You could use pure bash techniques to achieve this. By reading the string to array and doing the arithmetic operator using the $((..)) operator. You can run these commands directly on the command-line,

IFS=", " read -ra numArray <<<"8, 14-24, 30-45, 9"

unset count
for word in "${numArray[@]}"; do
   (( ${#word} == 1 )) && ((++count)) || count=$(( count +  ${word#*-} - ${word%-*} + 1  ))
done

printf "%s\n" "$count"

The idea is

  • The read with -a splits the string on the de-limiter set by IFS and reads it into the array numArray
  • A loop on each of the elements, for each element, if the element is just single character, just increment total count by 1
  • For numeric ranges, do manipulation as e.g. for number a-b use parameter expansion syntax ${word#*-} and ${word%-*} to extract b and a respectively and do b-a+1 and add it with count calculated already and print the element after the loop

  • You can put this in a bash script with she-bang set to #!/bin/bash and run the script or run it directly from the command-line

Upvotes: 1

Related Questions