user2862989
user2862989

Reputation: 9

How to split one word into multiple variables in bash shell?

Currently a variable is being set to something a string like this:

offs3.0

and I would like to split that into 2 variables

offs
3.0

How can i do it?

because i will use offs later.

if ("$1"=="offs")
here $1 is offs3.0

Upvotes: 1

Views: 345

Answers (4)

tripleee
tripleee

Reputation: 189327

Or just use the shell's built-in parameter substitution.

var='offs3.0'
echo "${var%%[.0-9]*}"
echo "${var##*[A-Za-z]}"

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 246764

using a bash regex

s=offs3.0
[[ $s =~ ^([^[:digit:]]+)(.*) ]] &&
   echo "${BASH_REMATCH[1]} - ${BASH_REMATCH[2]}"
offs - 3.0

Upvotes: 3

anubhava
anubhava

Reputation: 784998

Can be done using single sed also:

s='offs3.0'
(set -- $(sed 's/^\([a-z]*\)\(.*\)$/\1 \2/' <<< "$s") && echo "arg1=$1" "arg2=$2")

arg1=offs arg2=3.0

Upvotes: 0

imp25
imp25

Reputation: 2357

If you just want to test if a variable contains offs you can use:

if [[ "$1" =~ "offs" ]]
then
    # do something
fi

Upvotes: 1

Related Questions