3

I have the following emails.txt with:

[email protected]
[email protected]
[email protected];es
[email protected]
[email protected]
@pepito.com 

And a sed command to get

sed -n -r '/\w+@\w+\.\w+((\.\w+)*)?/p' emails.txt 

[email protected]
[email protected] 

But, it keeps displaying email with more than one .com

I don't want these emails :

[email protected]
[email protected];es
[email protected] 
@pepito.com 

I'm stuck here and I have no clue about how to get it.

2

3 Answers 3

6

With sed, you could do:

$ sed -nr '/^[^@]+@[^.]+\.com\s*$/p' file
[email protected]
[email protected]

The regex looks for one or more non-@ characters at the beginning of the line, then a @, then one or more non-. characters followed by .com and then 0 or more whitespace.


Other choices:

  • Perl

    perl -ne 'print if /^[^@]+@[^.]+\.com\s*$/' file
    
  • GNU grep

    grep -P '^[^@]+@[^.]+\.com\s*$' file
    
  • POSIX grep

    grep -E '^[^@]+@[^.]+\.com\s*$' file
    
  • awk

    awk '$0~/^[^@]+@[^.]+\.com\s*$/' file
    
12
  • There may not wihitespace at the end, but \r.
    – Pilot6
    Jun 14, 2015 at 14:50
  • I would use egrep instead.
    – Pilot6
    Jun 14, 2015 at 14:50
  • @Pilot6 not a problem, \s matches \r as well.
    – terdon
    Jun 14, 2015 at 14:50
  • @Pilot6 sure, or various other tools. You can use the same regex on all of them. Just don't use egrep, that's been deprecated in favor of grep -E (see man grep).
    – terdon
    Jun 14, 2015 at 14:53
  • I did not know that. I always use egrep, but I know that -E is same.
    – Pilot6
    Jun 14, 2015 at 14:54
5

I would use something like this :

sed -n -r '/\w+@\w+\.com$/p' emails.txt

[email protected]
[email protected]

It will retrieve every email in format [email protected]

In case you need something more "universal" and not only .com but also .fr or .uk you can use :

sed -n -r '/\w+@\w+\.\w+$/p' emails.txt

This will retrieve every email in format [email protected]

2
  • I would take this one I understand this one much better thank you man.
    – Heijs7
    Jun 15, 2015 at 13:44
  • So feel free to accept this answer if it actually answers and solves your problem... ;) Jun 16, 2015 at 20:08
3

The expression ((\.\w+)*)? matches additional sequences of the form .xyz after the first domain. If you want to match only those addresses with a single domain, then you can enforce that by replacing it with $ or (more robustly) \s*$

sed -n -r '/\w+@\w+\.\w+\s*$/p' emails.txt

to require that there is nothing (except possibly whitespace) between the first domain and the end of the line.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .