Domanda

function check()
{
    word=name@gmail.com
    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!

È stato utile?

Soluzione

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

$ var="name@gmail.com"
$ 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

Altri suggerimenti

You could use bash parameter expansion/substring removal:

$ var="name@gmail.com"

# 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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top