1834387 Members
2445 Online
110066 Solutions
New Discussion

Re: Joining text lines.

 
SOLVED
Go to solution
Evelyn Daroga
Regular Advisor

Joining text lines.

I have a text file which I need to read, and join 3 lines into a single record. I know of several ways to do this. The problems I am running into are: (1) the 2nd and 3rd lines have leading spaces which must be preserved, and (2) the lines are of varying length, and I need them to be 132,131,80 respectively before joining them, so that the resulting records will have fixed-length fields.

Using variable assignment drops the leading spaces on the 2nd and 3rd lines.
"pr -3tas " preserves the spaces and appends the lines, but doesn't address the varying line length problem.

I've played with pr, printf, sed, awk, nroff, and who-knows-what-else. I'm not very competent with most of these!

Any suggestions would be appreciated!

6 REPLIES 6
Robin Wakefield
Honored Contributor

Re: Joining text lines.

Hi Evelyn,

I may be misinterpreting your query, but, as a start, how about you do the following:

awk '
NR==1{printf("%-132s",$0)}
NR==2{printf("%-131s",$0)}
NR==3{printf("%-80s",$0)}
END{print}' filename

I don't know how many lines are in your file, and how you're selecting the ones you want to join together.

Rgds, Robin
Stefan Farrelly
Honored Contributor

Re: Joining text lines.


Maybe the join command will help. See manpage for it.
Im from Palmerston North, New Zealand, but somehow ended up in London...
Praveen Bezawada
Respected Contributor

Re: Joining text lines.

Hi
If you have more than 3 lines you can do

awk ' NR%3 == 0 { ... }
NR%3 == 1 { ... }
NR%3 == 2 { ... }' filename

...BPK...

A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Joining text lines.

Hi Evelyn,

This is rather easy with a 'here doc' script which calls awk. Use it like this:

3lines.sh < my_input_file > my_output_file

Clay
If it ain't broke, I can fix that.
Evelyn Daroga
Regular Advisor

Re: Joining text lines.

Thank you all very much! Rita's awk worked for one record (which is ok for one of our files), and Clay's attachment worked for the file with many records (I have no idea what it really does, but YAY!) Sorry, but the join command didn't seem to apply, and I didn't play much with the awk with the %3 stuff -- like I said I'm not competent in this stuff and need to closely analyze each of these solutions to see what they're really doing. I appreciate all the input.
Evelyn Daroga
Regular Advisor

Re: Joining text lines.

OOPS... I meant Robin's solution... Not "Rita's". Sorry, Robin!