5

I have a text file with one email address per line. How can I remove the domain part but not the TLD part of each line? In here, we would define TLD to be the last element of the string after the last dot character.

In other words, sample input:

foobar@example.org
john.smith@hotmail.com
chunkylover69@mail.dk
qwerty@yahoo.co.uk

Desired output:

foobar@org
john.smith@com
chunkylover69@dk
qwerty@uk
7
$ sed 's/@.*[.]/@/' file
foobar@org
john.smith@com
chunkylover69@dk
qwerty@uk

The regex @.*[.] captures everything from @ to a the last period . on the line. We replace that with @.

2

Using perl

perl -pe 's/(@).*\.(.*)$/\1\2/' foo

or inline

perl -i -pe 's/(@).*\.(.*)$/\1\2/' foo

Example

$ cat foo
foobar@example.org
john.smith@hotmail.com
chunkylover69@mail.dk
qwerty@yahoo.co.uk

$ perl -pe 's/(@).*\.(.*)$/\1\2/' foo
foobar@org
john.smith@com
chunkylover69@dk
qwerty@uk

RegEx explanation

/(@).*\.(.*)$/

  • 1st Capturing group (@)

    @ matches the character @ literally

  • .* matches any character (except newline)

    Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]

    \. matches the character . literally

  • 2nd Capturing group (.*)

    .* matches any character (except newline)

    Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]

  • $ assert position at end of the string

Regular expression visualization

Debuggex Demo

1

Using awk you can do it this way

$awk '{ sub(/\@.*\./,"@"); print }' file


foobar@org
john.smith@com
chunkylover69@dk
qwerty@uk

Using sub Substitute (find and replace), you can search for a pattern and replace.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.