Chris Seymour
Chris Seymour

Reputation: 85775

Append the end of one line to the start of the next with sed

I'm looking for sed only solutions for the following:

Corrupted Input:

A 123 dgbsdgsbg
A 345 gsgsdgdgs A 23
2 afaffaaf
A 324 fsgdggsdg A 345 avsa
fasf

Expected output:

A 123 dgbsdgsbg
A 345 gsgsdgdgs
A 232 afaffaaf
A 324 fsgdggsdg
A 345 avsafasf

How can the trailing A [0-9].* be appended to the start of the next line. So far I have:

$ sed -r 's/ (A [0-9]+.*)/\n\1/' file
A 123 dgbsdgsbg
A 345 gsgsdgdgs
A 23
2 afaffaaf
A 324 fsgdggsdg
A 345 avsa
fasf

Upvotes: 2

Views: 103

Answers (3)

potong
potong

Reputation: 58351

This might work for you (GNU sed):

 sed -r '$!N;s/ (A[^\n]*)\n/\n\1/;P;D' file

Upvotes: 3

fedorqui
fedorqui

Reputation: 289495

This can be an option:

$ sed -r ':a;$!N;s/ (A [0-9]+.*)\n(.*)/\n\1\2/;ta;P;D' file
A 123 dgbsdgsbg
A 345 gsgsdgdgs
A 232 afaffaaf
A 324 fsgdggsdg
A 345 avsafasf

It is an adaption of the last example from How to match newlines in sed:

sed ':begin;$!N;s/FOO\nBAR/FOOBAR/;tbegin;P;D'
# if a line ends in FOO and the next starts with BAR, join them

Upvotes: 3

devnull
devnull

Reputation: 123448

Did you try:

sed -e :a -e '$!N;s/\([0-9]\)\n\([0-9]\)/\1\2/;ta' -e 'P;D'

Example:

$ cat input
abc 123
456
def
123
ghi 123
jkl 456
789
$ sed -e :a -e '$!N;s/\([0-9]\)\n\([0-9]\)/\1\2/;ta' -e 'P;D' input
abc 123456
def
123
ghi 123
jkl 456789

EDIT: You modified the example in the question later. For your modified input, try:

$ sed -e 's/ \(A .*\)/\n\1/' -e :a -e '$!N;s/\n\([^A]\)/\1/;ta' -e 'P;D' newinput
A 123 dgbsdgsbg
A 345 gsgsdgdgs
A 232 afaffaaf
A 324 fsgdggsdg
A 345 avsafasf

Upvotes: 3

Related Questions