Showing results for 
Search instead for 
Do you mean 

shell script

Go to Solution
Occasional Advisor

shell script

I have a string like

I need to extract the mailid seperated by a space for any given user like ax-a1.

I have tried to use
Test=`grep a1-ax mailids.txt`
echo $Test | awk '{print substr($0,":",index($0,";"))}'

but it doesn't seem to work. Can you please suggest??

Honored Contributor

Re: shell script


The second argument to substr is an offset numner, and you passed it a piece of string.
That's not goign to work.

Please explain a little more clearly what you expact for output and where the input comes from.
- A single long string with multiple usernames + email?
- When ax-a1 is select, which are we supposed to return:, or all of ""?

You may readily find a solution by using a regexpr for field seperator. Check out the following example:

$ cat x
ax-a1:; ax-a2:;
$ awk -F'[:; ]+' '{print $3}' x
$ awk -F'[:;]' '{print $3}' x
$ awk -F'[:;]' '{print $2}' x

Hope this helps some...

Honored Contributor

Re: shell script


if your string has an entry
und you grep for
you won't get results :-)

This will give you the second field stripped by the last character, which is ";" in your case:

awk -F: -v user=ax-a1 '$1 == user {print substr($2,1,length($2)-1)}' mailids.txt

mfG Peter
The Universe is a pretty big place, it's bigger than anything anyone has ever dreamed of before. So if it's just us, seems like an awful waste of space, right? Jodie Foster in "Contact"
Honored Contributor

Re: shell script

Buildin up on the external passed usename you could 'walk' the field in steps of 2 looking for a username match.
Note, I had to strip spaces from the username for it to match easily:

$awk -F'[:;]' -v user=ax-a2 '{i=0; while (i++

Or you could have 'fields' be user:email by using ';' as FS (field seperator) and then splitting on ":" to look at the parts:

$ awk -F\; -v user=ax-a1 '{i=0; while (i++

Acclaimed Contributor

Re: shell script


How about:

# STR="ax-a1:;ax-a2:;"

# echo ${STR} | perl -nle 'BEGIN{$u=shift};print $1 if m/$u:(.+?);/' ax-a1

...would return:


Honored Contributor

Re: shell script

Here's a way of doing it with sed:

# echo $Test | sed -n 's/\(.*\): \(.*\);/\2/p'

...and with awk

echo $Test | awk -F": " '{print z[split($2,z,";")-1]}'
Honored Contributor

Re: shell script

cut -d":" -f 2

you'll still have a ';' at the end but that's removed quickly with sed or something similar.
Occasional Advisor

Re: shell script

Thanks everyone. Got it working now.