2

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:

* !^FROM_MAILER

The full contents of the file I want changed from:

:0
* !^FROM_MAILER
! [email protected]

to:

:0
! [email protected]

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.

1
  • 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.) Nov 20, 2015 at 12:06

1 Answer 1

4

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' {} +
4
  • 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. Nov 20, 2015 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, 2015 at 14:33
  • @LaurenceCope See my edit
    – chaos
    Nov 20, 2015 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 :-) Nov 20, 2015 at 15:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .