34.24. sed Newlines, Quoting, and Backslashes in a Shell Script
Feeding sed (Section 34.1) newlines is easy; the real trick is getting them past the C shell and its derivatives (tcsh has the same problem, on the systems where we've tested it).
The sed documentation says that in order to insert newlines in substitute commands, you should quote them with backslashes. [Surround the commands with single quotes ('), as Chris has. If you use double quotes ("), this script will become s/foo/bar/ because of the way quoting works with backslashes and newlines (Section 27.12). -- JP]:
+sed -e 's/foo/b\ a\ r/'
Indeed, this works quite well in the Bourne shell and derivatives, such as bash, which do what I consider the proper thing (Section 27.12) with this input. The C shell, however, thinks it is smarter than you are and removes the trailing backslashes (Section 27.13), and instead you must type:
+sed -e 's/foo/b\\ a\\ r/'
Probably the best solution is to place your sed commands in a separate file (Section 34.3) to keep the shell's sticky fingers off them.
Copyright © 2003 O'Reilly & Associates. All rights reserved.