A.Krasniqi
A.Krasniqi

Reputation: 165

How to get emails that do & don't end with the desired domain?

I have a list of emails on a file emails.txt, how can I get emails that end with @gmail.com , and emails that DON'T end with @gmail.com , in two different files, using GREP or something similar

For ex.

***emails.txt***
[email protected]
[email protected]
[email protected]
[email protected]

I need two different outputs like:

***emails-gmail.txt***
[email protected]
[email protected]

and

***emails-other.txt***
[email protected]
[email protected]

Upvotes: 1

Views: 167

Answers (3)

campovski
campovski

Reputation: 3163

THIS DOES NOT WORK!!

You can do it with grep only and then redirect STDOUT to file like this:

  • Mails from @gmail.com:

    grep @gmail.com emails.txt > emails-gmail.txt
    
  • Mails not from @gmail.com:

    grep -v @gmail.com emails.txt > emails-other.txt
    

    What -v does is it returns lines that do not contain @gmail.com.


The above solution didn't work as expected, because grep uses regex and in regex, a dot . means match any character. We can use substitute grep for fgrep or grep -F that take argument as literal string instead of as regex! Then it works as intended. Additionally you can escape the regex dot with \.. Then you can again do

grep @gmail\.com emails.txt > emails-gmail.txt

Upvotes: 1

Ed Morton
Ed Morton

Reputation: 204578

The right approach is:

awk '{print > ("emails-" (/@gmail\.com$/ ? "gmail" : "other") ".txt")}' emails.txt

That will parse your input file once, generating both output files as it goes, and will correctly handle the potential false matches that the other solutions posted so far would fail on.

Upvotes: 1

Stuart
Stuart

Reputation: 6780

To get the emails that contain 'gmail.com', do:

cat emails.txt  | grep @gmail.com

and to get the emails that DON'T contain 'gmail.com', do:

cat emails.txt  | grep -v @gmail.com

Upvotes: 1

Related Questions