0

I am novice to linux scripting. For the below example, i need to split the string as per "-" and store the output in an array as a separate element. Later, i need to validate each element in an array if its an integer or alphanumeric. if its integer, i need to ignore that element and print only non-integer elements. The following script which i am trying is not giving expected output which should be like 'grub2-systemd-sleep-plugin'.

item = grub2-systemd-sleep-plugin-2.02-153.1
IFS='-'
read -rasplitIFS<<< "$item"
for word in "${splitIFS[@]}"; do echo $word; done

2 Answers2

0

Taking a stab at this here... Depends on how your numbers may be defined, but I believe you could use something like this to removing numbers from the output. I'm not sure if there is a more efficient way to achieve this

for word in ${splitIFS[@]}
  do 
    c=$(echo $word | grep -c -E "^[0-9]+\.{0,}[0-9]+$")
    [ $c -eq 0 ] && echo $word
  done
Ozzy
  • 26
  • 3
0

If you're using bash, it will be faster if you use built-in tools rather than subshells.

line=grub2-systemd-sleep-plugin-2.02-153.1-foo-1
while [[ -n "$line" ]]
do if [[ "$line" =~ ^[0-9.]+- ]]
   then line="${line#*-}"
   elif [[ "$line" =~ ^[0-9.]+$ ]]
   then break
   elif [[ "$line" =~ ^([[:alnum:]]+)- ]]
   then echo "${BASH_REMATCH[1]}";
        line="${line#*-}"
   elif [[ "$line" =~ ^([[:alnum:]]+)$ ]]
   then echo "${BASH_REMATCH[1]}";
        break
   else echo "How did I get here?"
   fi
done

or if you prefer,

shopt -s extglob
line=grub2-systemd-sleep-plugin-2.02-153.1-foo-1
while [[ -n "$line" ]]
do case "$line" in
   +([0-9.])-*)      line="${line#*-}"  ;;
   +([0-9.]))        break              ;;
   +([[:alnum:]])-*) echo "${line%%-*}"
                     line="${line#*-}"  ;;
   +([[:alnum:]]))   echo "$line"
                     break              ;;
   *)                echo "How did I get here?" ;;
   esac
done
Paul Hodges
  • 13,382
  • 1
  • 17
  • 36