user5752691
user5752691

Reputation: 31

How to I save grep regex matched result to a variable?

I have a variable : email="[email protected]" and I want to get its username portion to be stored in another variable.

I used the following grep command:

$ $email | grep '.*@'

Which gave me following output.

yask123@gmail.com

I want to save the matched string in a variable.

I tried

res=`echo $email | grep '.*@'`

which didn't work.

Upvotes: 2

Views: 2439

Answers (2)

Diego Torres Milano
Diego Torres Milano

Reputation: 69208

Just in case you want to do something more complex than shell match, which is absolutely valid applied to your example:

res=$(echo $email | sed 's/\(.*\)@.*/\1/')

Upvotes: 1

Cyrus
Cyrus

Reputation: 88636

Try this:

email="[email protected]"
echo "${email%@*}"

Output:

yask123

See: 3.5.3 Shell Parameter Expansion

Upvotes: 2

Related Questions