D_22 D_22 - 3 months ago 8
Linux Question

How would I split a word from number in bash and create a variable from it?

I have a word

FOO123USR
I would like to split the
foo
and have it in its own variable and also the
123
in its own variable and finally I would like to get rid of the
USR
. I'm having trouble trying to accomplish this.

This is how my script looks so far but I am getting a blank output

#!/bin/bash


#var holding

RED='\033[0;31m'
NC='\033[0m'
var2=$(echo $START_VAR | grep -o -E '[0-9]+')
var1=${START_VAR//[A-Z]/}


if [ "$EUID" -ne 0 ];
then
echo -e "${RED} YOU MUST RUN AS ROOT USER ! ${NC}\n"
exit
fi

# We are getting the username here

read -p "Type the username <example: FOO123USR> [ENTER]: " START_VAR


echo "$va2"
echo "$var1"

Answer

One way to do this type of tinkering:

START_VAR=FOO123USR
var1=${START_VAR%%[0-9]*} # remove from first number to end
var2=${START_VAR//[A-Z]/} # remove ALL uppercase letters

More examples and info: https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html

:)
Dale