Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string and store each split into variables

Tags:

string

bash

cut

function check()
{
    [email protected]
    arr=$(echo $word | tr "@" "\n")

    for x in $arr
    do
        echo "> $x"
    done
}

for output I get

name
gmail.com

I want to store each of them into separate variables. How do I do that?

Do I go

for x in $arr
do
    echo "> $x"
    first=$x
    second=$x
done

Quite lost here. Help me out please!

like image 740
Dan Avatar asked Jul 10 '26 12:07

Dan


2 Answers

You can use the following read sentence, in which the @ is defined as field separator:

$ var="[email protected]"
$ IFS="@" read var1 var2 <<< "$var"

Then see how the values have been stored:

$ echo "var1=$var1, var2=$var2"
var1=name, var2=gmail.com

You can also make use of cut:

$ name=$(cut -d'@' -f1 <<< "$var")
$ email=$(cut -d'@' -f2 <<< "$var")
$ echo "name=$name, email=$email"
name=name, email=gmail.com
like image 190
fedorqui 'SO stop harming' Avatar answered Jul 13 '26 17:07

fedorqui 'SO stop harming'


You could use bash parameter expansion/substring removal:

$ var="[email protected]"

# Remove everything from the beginning of the string until the first
# occurrence of "@"
$ var1="${var#*@}"

# Remove everything from the end of the string until the first occurrence
# of "@"
$ var2="${var%@*}"

$ echo "$var1"
gmail.com

$ echo "$var2"
name
like image 35
Saucier Avatar answered Jul 13 '26 17:07

Saucier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!