1753759 Members
4789 Online
108799 Solutions
New Discussion юеВ

Re: join lines in a file

 
SOLVED
Go to solution
Saini
New Member

join lines in a file

Hi

I have a problem similar to the one in this thread.
http://forums13.itrc.hp.com/service/forums/questionanswer.do?threadId=1202845

But, in my case the file is of this format.
---
line1.1
line1.2
line1.3

line2.1
line2.2
line2.3
line2.4

line3.1
line3.2
---
I want the following output
---
line1.1line1.2line1.3

line2.1line2.2line2.3line2.4

line3.1line3.2
---
So, basically I've to join the lines until a empty line is encountered. Then , i have to skip it and start joining other lines. I am unable to do it with my limited knowledge of awk.
Any help is appreciated.
Thanks
Saini
7 REPLIES 7
Dennis Handly
Acclaimed Contributor
Solution

Re: join lines in a file

awk '
{
if ($0 == "") {
print save
print
next
}
save = save $0 # concatenate
}
END { print save }' file
James R. Ferguson
Acclaimed Contributor

Re: join lines in a file

Hi:

One way:

# perl -le '$/="";while (<>) {chomp;s/\n/ /g;print}' file

Regards!

...JRF...
Suraj K Sankari
Honored Contributor

Re: join lines in a file

Hi ,

Dennis: I am sorry to say from your awk the output is comming like, see the below

line1.1 line1.2 line1.3

line1.1 line1.2 line1.3 line2.1 line2.2 line2.3 line2.4

line1.1 line1.2 line1.3 line2.1 line2.2 line2.3 line2.4 line3.1 line3.2 line1.1

line1.1 line1.2 line1.3 line2.1 line2.2 line2.3 line2.4 line3.1 line3.2 line1.1 line1.2 line1.3

line1.1 line1.2 line1.3 line2.1 line2.2 line2.3 line2.4 line3.1 line3.2 line1.1 line1.2 line1.3 line2.1


Saini required this output

line1.1line1.2line1.3

line2.1line2.2line2.3line2.4

line3.1line3.2


Saini please use this awk script for the same output you required

awk '
{
if (substr($0,1,1)=="l") printf "%s ",$1
else
printf "\n\n"
}'

Suraj
Dennis Handly
Acclaimed Contributor

Re: join lines in a file

>Suraj: I am sorry to say from your awk the output is coming like

Oops, forgot to reset "save":
awk '
{
if ($0 == "") {
print save
print
save = ""
next
}
save = save $0 # concatenate
}
END { print save }' file
James R. Ferguson
Acclaimed Contributor

Re: join lines in a file

Hi (again) Suraj:

OK, I see from your last post that your do not want a space between the tokens on each line.

I also see from your last post that you *do* want the blank line preserved between groups.

Lastly, it appears that you don't want a trailing blank line, so I'll suppress that.

Those are trivial adjustments. Hence:

# perl -le '$/="";while (<>) {s/\n//g;printf "%s\n",(eof) ? $_ : "$_\n"}' file

Regards!

...JRF...

Saini
New Member

Re: join lines in a file

Thanks a lot everybody. You've solved my problem.

Saini
Saini
New Member

Re: join lines in a file

Thanks a ton.