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!
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With