mitas1c
mitas1c

Reputation: 335

How to join lines that end with - but do not start with space in SED?

I am working on sed script that merges adjacent lines of text ending with the - character, if there are no white characters (space, tab) before it, together with the next line.

I have a script that doesn exactly that, however it doesn't filter properly.

My script

 #!/bin/bash
 file=$1
 sed ':a;/-$/{N;s/-\n//;ba}' $file

This is my file input

line1- 
line2

line3-
line4

line5 -
 line6

And this is the result I want to see

line1- 
line2

line3line4

line5 -
 line6

And this is what I get

line1- 
line2

line3line4

line5 line6

Upvotes: 0

Views: 139

Answers (4)

potong
potong

Reputation: 58391

This might work for you (GNU sed):

sed -E ':a;N;s/(\S)-\n/\1/;ta;P;D' file

Append the following line and if the current line ends in a non-space character followed by a -, remove the - and the following newline and go again.

Otherwise, print/delete the first line and repeat.

Upvotes: 1

Walter A
Walter A

Reputation: 20002

With GNU sed:

sed -rz 's/ -\n/ -\r/g; s/-\n//g; s/ -\r/ -\n/g' $file

Upvotes: 1

M. Nejat Aydin
M. Nejat Aydin

Reputation: 10123

This sed command should do the job:

sed '
:a
/[^[:blank:]]-$/!b
$!N
s/-\n//
$!ba' file

Upvotes: 2

The fourth bird
The fourth bird

Reputation: 163277

You might use a pattern to capture a non whitespace char in a group, and use that group in the replacement without using a label:

sed -E '/-$/{N;s/([^[:space:]])-\n/\1/}' $file

Output

line1- 
line2

line3line4

line5 -
 line6

See a sed demo.

Upvotes: 1

Related Questions