I have a bash script which is initiated with arguments, I have a function to process arguments. I place the arguments in an array args=("$@"). and I have a function which can check if the argument does contain certain elements.

containsElement () {
  local e
  for e in "${@:2}"; do [[ "$e" == "$1" ]] && { ipos="$i"; return 0; }
  return 1

I wanted to improve my function with the ability that; After finding the argument, check the next arguments and see if they contain numbers until the next non numerical element in array is found, put them in an array of opt[1], opt[2], ... It's better explained in an example;

sh script.sh plt 2 3 g40 All 32

then I want the function give me

if containsElement "plt" "${args[@]}" ; then
containsElement "plt" "${args[@]}"
echo ${opt[@]}

give me

2 3 g40

The number are options for each argument. I can write something to do this but it turns to an ugly code, I wanted to learn a nice way to do it.


I'll do it with regexes, for example:

echo plt 2 3 g40 All 32|perl -ne's/(\w+) ([\d ]+)(\w+)/print "$1$2$3\n"/egx;'

plt 2 3 g40
All 32

Not sure if it's what you are looking for? You can omit printing the first string for each parameter group, with:

echo plt 2 3 g40 All 32|perl -ne's/(\w+) ([\d ]+)(\w+)/print "$2$3\n"/egx;'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.