1

I have a very lengthy string (length is also not fixed) I want to extract a substring lying between 'email' and '@gmail.com'

Suppose it is

xhxjcndjcnkjcnd cjkjcdckjncx email:[email protected] djc

I want to extract the 'substring' in the String.. Can I do this using regular expression , using sed tool.?

1
  • Do you have other mail than gmail? If so, solution using gmail as search will no work. Commented Sep 20, 2013 at 12:48

6 Answers 6

3
perl -lne 'print $1 if(/email:(.*?)\@gmail.com/)'

Tested below:

> echo "xhxjcndjcnkjcnd cjkjcdckjncx email:[email protected] djc" | perl -lne 'print $1 if(/email:(.*?)\@gmail.com/)'
substring
>
Sign up to request clarification or add additional context in comments.

Comments

1

VALUE="xhxjcndjcnkjcnd cjkjcdckjncx email:[email protected] djc"

echo $VALUE | awk -F":" '{print $2}' |cut -d@ -f1

1 Comment

The sed just do the same as awk, so why not two awk like this awk -F: '{print $2}' | awk -F@ '{print $1}' or two sed?
1

Another awk

awk -F":" '{split($2,a,"@");print a[1]}' file
substring

It you have many lines to search for gmail addresses

awk -F":" '/gmail\.com/ {split($2,a,"@");print a[1]}'
substring

Comments

1

Using sed:

INPUT="xhxjcndjcnkjcnd cjkjcdckjncx email:[email protected] djc"
USERNAME=$(sed -n "s/.*\email:\(.*\)@gmail\.com.*/\\1/p" <<< $INPUT)
echo $USERNAME

1 Comment

This returns [email protected] not correctly substring. You should also change backtics to paranthese $(data) Eksample MAIL=$(sed -n "s/.*\email:\(.*@gmail\.com\).*/\\1/p" <<< $INPUT)
1

The shell can handle this:

$ line='xhxjcndjcnkjcnd cjkjcdckjncx email:[email protected] djc'
$ name=${line#*email:}       # remove the prefix ending with "email:"
$ name=${name%@gmail.com*}   # remove the suffix starting with "@gmail.com"
$ echo $name
substring

Comments

0

I think grep (with positive lookahead and positive lookbehind) is the correct tool for the job:

$ grep -oP '(?<=email:).*?(?=@gmail\.com)'<<< "xhxjcndjcnkjcnd cjkjcdckjncx email:[email protected] djc"
substring

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.