Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed: joining lines depending on the second one

Tags:

I have a file that, occasionally, has split lines. The split is signaled by the fact that the line starts with '+' (possibly preceeded by spaces).

line 1
line 2
  + continue 2
line 3
...

I'd like join the split line back:

line 1
line 2 continue 2
line 3
...

using sed. I'm not clear how to join a line with the preceeding one.

Any suggestion?

like image 292
Remo.D Avatar asked Apr 03 '12 19:04

Remo.D


People also ask

Can sed match multiple lines?

By using N and D commands, sed can apply regular expressions on multiple lines (that is, multiple lines are stored in the pattern space, and the regular expression works on it): $ cat two-cities-dup2.

How do you sed multiple times?

You can tell sed to carry out multiple operations by just repeating -e (or -f if your script is in a file). sed -i -e 's/a/b/g' -e 's/b/d/g' file makes both changes in the single file named file , in-place.


2 Answers

This might work for you:

sed 'N;s/\n\s*+//;P;D' file

These are actually four commands:

  • N
    Append line from the input file to the pattern space
  • s/\n\s*+//
    Remove newline, following whitespace and the plus
  • P
    print line from the pattern space until the first newline
  • D
    delete line from the pattern space until the first newline, e.g. the part which was just printed

The relevant manual page parts are

  • Selecting lines by numbers
  • Addresses overview
  • Multiline techniques - using D,G,H,N,P to process multiple lines
like image 52
potong Avatar answered Oct 13 '22 20:10

potong


Doing this in sed is certainly a good exercise, but it's pretty trivial in perl:

perl -0777 -pe 's/\n\s*\+//g' input
like image 44
William Pursell Avatar answered Oct 13 '22 19:10

William Pursell