Kelsey Cannata
Kelsey Cannata

Reputation: 7

Bash cut and remove characters

Here is the user email for example...

[email protected]

I want to cut out the mburkhar and also remove the imap. in the email to look like this in a new file. I have been working on this for a while but there are so many different commands I am confused as to what I should actually be using for this problem.

mburkhar [email protected]

Upvotes: 0

Views: 422

Answers (3)

Sylvain Bugat
Sylvain Bugat

Reputation: 8164

You can use the sed command to do this:

echo "[email protected]" | sed -e 's/^\(.*\)@imap[^\.]*.\(.*\)/\1 \1@\2/'
mburkhar [email protected]

This will capture the part before the @ ignore any string starting with imap just after the @ and capture the end of the address.

If no imap is found the output will be like this:

echo "[email protected]" | sed -e 's/^\(.*\)@imap[^\.]*.\(.*\)/\1 \1@\2/'
[email protected]

Upvotes: 1

Peter Bowers
Peter Bowers

Reputation: 3093

I would use a quick sed script:

sed 's/\([^@]*\)@imap[0-2]\.\(.*\)$/\1 \1@\2/'

Upvotes: 1

Charles Duffy
Charles Duffy

Reputation: 295443

[email protected]
s_name=${s%%@*}
s_adjusted=${s//@imap1./@}
echo "Name is $s_name; adjusted email address is $s_adjusted"

When run, this will have the output:

Name is mburkhar; adjusted email address is [email protected]

...of course, for your originally requested output, you could

echo "$s_name $s_adjusted"

...or, to implement this as a one-liner, assuming again your original value in the variable $s:

echo "${s%%@*} ${s//@imap1./@}"

These are parameter expansion operations, performed internally to bash, and thus more efficient than using any external process such as sed.

Upvotes: 2

Related Questions