sed command to arrange words

Hi

I have a text file as given below:

Input format

I
have
a
text
file
as
given
below
.

This
is
a
sample
test
file
.

There is a space between the sentences in the above format.

I want to write sed command to arrange these words in such a way that they appear as given below.

Output Format:

I have a text file as given below .
This is a sample test file .

Thanks in advance. :slight_smile:

sed -e ':L' -e '/\./{p;d;}' -e 'N;s/\n/ /;bL' file

label L
If there is . then p rint, d elete and next cycle.
Append N ext line (with embedded \n), s ubstitute the \n by a space, jump to label L
With some debug code you see how it works:

sed -e ':L' -e '/\./{p;d;}' -e '=;p;N;s/\n/ /;bL' file

print current line number and current pattern space.

1 Like

I got the following output:

I
have
a
text
file
as
given
below
.

This
is
a
sample
test
file
.
I have a text file as given below .
 This is a sample test file .

But I want to get the following output only:

I have a text file as given below .
This is a sample test file .
sed -e ':L' -e '/\./{p;d;}' -e 's/^ //' -e 'N;s/\n/ /;bL'

Will do the trick!

---------- Post updated at 04:46 PM ---------- Previous update was at 04:44 PM ----------

Sorry, new here--

sed -e ':L' -e '/\./{p;d;}' -e 's/^ //' -e 'N;s/\n/ /;bL'

let's see if this is kosher!

1 Like

I got the following output:

I
have
a
text
file
as
given
below
.

This
is
a
sample
test
file
.
I have a text file as given below .
This is a sample test file .

How do I get only:

I have a text file as given below .
This is a sample test file .

Thanks.:slight_smile:

sed -e ':L' -e '/\./{p;d;}' -e 's/^ //' -e 'N;s/\n/ /;bL'

Ah git it!!

1 Like

Or substitute the leading space only once before the print

sed -e ':L' -e '/\./{s/^ //;p;d;}' -e 'N;s/\n/ /;bL' file

You don't get the input repeated in the output. (What did you do?)

Not sed, but this awk alternative also works with your given input.

awk '{$1=$1}1' RS= file

Note: it only works if there are two consecutive newlines (a completely empty line) between two vertical sentences, as is the case in your sample.

Hi,
Another way in bash builtin works with your given input (for fun):

while read -d \. foo ; do echo $foo.; done <file ; [ "$foo" ] && echo $foo

Regards.

An alternative in Perl.

perl -00 -nae 'print "@F\n"' my_Perl.file