9

I have a CSV file contains domains and webmails, like this:

site1.com,mail.site1.com
site2.com,testmail.com
site3.com,mx.site3.com
site4.com,smtp.site4.com
site5.com,foomail.com
site6.com,barmail.com
site7.com,webmail.site7.com
site8.com,01mx.site8.com
site9.com,foobarmail.com
site10.com,mx-smtp222.site10.com

I want to get rows where the webmails column contains the domains column of the same row. For the example above, the output should be:

site1.com,mail.site1.com
site3.com,mx.site3.com
site4.com,smtp.site4.com
site7.com,webmail.site7.com
site8.com,01mx.site8.com
site10.com,mx-smtp222.site10.com
11

With awk:

awk -F, '$2 ~ $1"$"' file.csv
  • -F, sets the field separator as ,

  • $2 ~ $1"$" tests if the second field ends with the first field; if so, print the record (default action)


With grep, grep by default print only matched lines:

grep -E '^([^,]+),.*\1$' file.csv

With sed, printing lines matching the condition:

sed -nE '/^([^,]+),.*\1$/ p' file.csv

Example:

% cat file.txt
site1.com,mail.site1.com
site2.com,testmail.com
site3.com,mx.site3.com
site4.com,smtp.site4.com
site5.com,foomail.com
site6.com,barmail.com
site7.com,webmail.site7.com
site8.com,01mx.site8.com
site9.com,foobarmail.com
site10.com,mx-smtp222.site10.com

% awk -F, '$2 ~ $1"$"' file.txt
site1.com,mail.site1.com
site3.com,mx.site3.com
site4.com,smtp.site4.com
site7.com,webmail.site7.com
site8.com,01mx.site8.com
site10.com,mx-smtp222.site10.com

% grep -E '^([^,]+),.*\1$' file.txt
site1.com,mail.site1.com
site3.com,mx.site3.com
site4.com,smtp.site4.com
site7.com,webmail.site7.com
site8.com,01mx.site8.com
site10.com,mx-smtp222.site10.com


% sed -nE '/^([^,]+),.*\1$/ p' file.txt 
site1.com,mail.site1.com
site3.com,mx.site3.com
site4.com,smtp.site4.com
site7.com,webmail.site7.com
site8.com,01mx.site8.com
site10.com,mx-smtp222.site10.com

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.