11

I am new to using sed but I have been experimenting sed's s/..../..../ (substitute) to modify a full sentence if it's on one line but I am unaware an alternative solution on how to modify a sentence that may have been separated on two lines such as:

This:

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

is actually written as this:

Lorem Ipsum is simply dummy text of the 
printing and typesetting industry.

How can you detect for this or code it to replace the entire sentence even if it's on two lines instead of one?

  • Great sed reference book: Definitive Guide to sed Tutorial and Reference by Daniel A. Goldman ISBN: 978-1-939824-01-1 (EPUB version) 08148804441822 – Joe Sep 27 '13 at 8:01
16

The following command will work in both situations:

sed '/Lorem.*/ {N; s/Lorem.*industry\./string to replace/g}' filename

More explanations: How can I use sed to replace a multi-line string?

12

While sed can match patterns on multiple lines (using the commands N or H to append successive lines before matching), this is well outside its comfort zone. Attempt it only if you like pain.

Perl can do this kind of things nicely. Use the -p switch to make it process standard input one record at a time and print the modified record (à la sed), and -000 to turn on paragraph mode (where records are separated by blank lines). In a regular expression, \s matches any whitespace character including a newline.

perl -p -000 -e 's/Lorem\s+Ipsum\s+is\s+simply\s+dummy\s+text\s+of\s+the\s+printing\s+and\s+typesetting\s+industry\./Replacement text/g'

If you want to put a newline in the replacement text when the original contains one, that's more complicated. How to do it depends on your requirements as to where to put the newline.

  • @terdon Ah, I meant to allow multiple whitespace but forgot. Thanks, fixed. – Gilles Sep 18 '13 at 22:55
  • The question is about sed. It is also tagged with sed, not with perl. – Radu Rădeanu Sep 19 '13 at 8:25
0

sed cannot easily read across multiple lines. Use perl -i -0pe 's/.../.../...' instead.

  • 7
    sed can read across multiple lines! – Radu Rădeanu Sep 18 '13 at 22:31
  • 3
    @RaduRădeanu Technically, yes. But it's rarely worth the trouble. – Gilles Sep 18 '13 at 22:46
  • 3
    @Gilles If using perl is more simple for you, this doesn't means that sed rarely worth the trouble. – Radu Rădeanu Sep 19 '13 at 8:19

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.