I would like to find and replace text within many .procmailrc files, and using grep and sed.

I would like to remove the following line (including the new line break at the beginning) from the .procmailrc files:


The full contents of the file I want changed from:

! myemail@email.com


! myemail@email.com

The command I am running is:

grep -lir '\n* !^FROM_MAILER' .procmailrc | xargs sed -i 's/\n* !^FROM_MAILER//g'

But it is not replacing the *. In leaves the line in with just the * on it. If I escape the * as follows, that also does not work:

grep -lir '\n\* !^FROM_MAILER' .procmailrc | xargs sed -i 's/\n\* !^FROM_MAILER//g'

So I trying to find out how to do the find and replace to remove the entire line with the * in it.

  • Part of the answer is that sed operates on lines of text, where a line of text is a sequence of characters between one newline and another (or before the first newline); therefore, you generally don't include \n in sed commands.  (There are some exceptions.)  Your commands with \* might have come close to working if you had left out the \n.  (Similarly, don't think in terms of deleting \n characters; think in terms of deleting lines.) – G-Man Says 'Reinstate Monica' Nov 20 '15 at 12:06

With sed alone:

sed -i '/^* !^FROM_MAILER$/d' file

To remove the whole line containing the exact string * !^FROM_MAILER, with nothing before and after that string. The d command deletes the line.

Edit: If you want to do the replace in all files recusively, use the following:

find /path -type f -exec sed -i '/^* !^FROM_MAILER$/d' {} +
  • How would I do it for all files in a folder with sed alone? The grep command is to search all files and replace in all files. Thanks. – Laurence Cope Nov 20 '15 at 14:32
  • @LaurenceCope just riun the command on all files. Those that don't contain the pattern will be left untouched. sed is very fast, it won't make much difference in the time it takes. – terdon Nov 20 '15 at 14:33
  • @LaurenceCope See my edit – chaos Nov 20 '15 at 14:38
  • Don't you need a backslash before the asterix? or is it not necessary when its the first character? (I suppose I should just go and look that up :-) – Murray Jensen Nov 20 '15 at 15:54

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.