pasaico
pasaico

Reputation: 61

Checking the validity of emails in multiple txt files

I have a lot of txt files contain emails separated by space and I would like to check whether there is an invalid email inside it.

With this I check whether file.txt is empty or not:

for file in *.txt; do
    email=(grep $file)
    if [ -s "$file" ]; then
        echo "OK $file"
     else   
        echo "-- EMPTY $file"

My question is do I need to use grep for checking the validity of emails inside the file?

elif
        if [[ grep $file =~ "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$" ]]
    then
        echo "Email address inside $file is valid."
    else
        echo "Email address inside $file contain $email is invalid."
    fi
done

Upvotes: 0

Views: 292

Answers (1)

Dean Taylor
Dean Taylor

Reputation: 42021

Depending on your use case I would probably use a sequence like this:

  1. grep for all valid email addresses and store them in new text file.
  2. use diff to compare against original file to view invalid email addresses (if needed).

For your regex I would change to use word boundaries:

From: ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$

To: \b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b

So you aren't matching whole lines.

Upvotes: 1

Related Questions