I have a file with a list of emails in it and each line has an email in it. I want to remove lines that contain the string example.com or test.com.

I tried this:

sed -i 's/example\.com//ig' file.txt 

But it will remove only the string example.com, how can I remove the entire line?


With GNU sed:

sed '/example\.com/d;/test\.com/d' -i file.txt

will remove the lines with example.com and test.com.

From man sed:

d      Delete pattern space.  Start next cycle.
  • 1
    This will also delete line contain example (or test) follow by any character then com. Example echo 'exampleAcom' | sed '/example.com/d' – cuonglm Aug 21 '15 at 18:12
  • Gah, silly me absent-mindedly not escaping the dot. Thanks for noticing! – Walther Aug 21 '15 at 18:16

POSIXly, you can use grep:

grep -Eiv '(example|test)\.com' <in >out
  • 2
    Be careful not to use the same file for input and output, or it will be truncated before grep can read it. – Peter Cordes Aug 21 '15 at 18:25

Your regex only matches example.com and sed replaces only example.coms with empty string. Your regex should match any line containing example.com or test.com

sed -i 's@.*\(test\|example\)\.com.*@@i' file.txt
  • Your answer does not delete matching lines; it only makes them blank. – It also does not handle case insensitive text (as per the OP's example). –. The g is redundant/meaningless, because sed‍'s regex is greedy and therefore the leading and trailing .* will cause the 1st occurrence of a text match to match the entire line. ‍ – Peter.O Aug 21 '15 at 23:40
  • Thanks for feedback. I haven't paid attention to case sensivity. g is my habit, you are right, it is not neccesary. Also I thought, blanking line was what OP wanted. Now everything is clear. Thanks – Esref Aug 22 '15 at 6:13

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.