Operating System - HP-UX
1845812 Members
4380 Online
110250 Solutions
New Discussion

Scripting help, joining two lines

 
SOLVED
Go to solution
Belinda Dermody
Super Advisor

Scripting help, joining two lines

I am requesting a simple sed or awk command that will take a file and join every two lines into one line. I would like the contents of the 2nd line appended to the first line.

Oct1620018:20AM
va_q5n
Oct1620018:17AM
va_qeq
Oct1620018:28AM
va_qv7
Oct1620018:10AM
va_rq4
Oct1620018:19AM
va_rw1
6 REPLIES 6
David Lodge
Trusted Contributor
Solution

Re: Scripting help, joining two lines

As in all things to do with shell you have several options:

1) paste:
paste -s -d " \n"
will join the files with a space between the lines

2) awk
awk '{ first=$0; getline; print first $0 }'

Potentially you can use pr, join or sed to do this too...

dave
James R. Ferguson
Acclaimed Contributor

Re: Scripting help, joining two lines

Hi James:

# awk '{if (NR%2==1) {HOLD=$0} else {print HOLD,$0}} END {if (NR
%2==1) {print HOLD}}' /tmp/myfile > /tmp/myfile.new

Regards!

...JRF...
Belinda Dermody
Super Advisor

Re: Scripting help, joining two lines

Thanks David and James, Both awk statements work but I gave David the full points because he was first and his command was less key strokes.
Once again thanks.
A. Clay Stephenson
Acclaimed Contributor

Re: Scripting help, joining two lines

Hi James:

How about purely in the shell reading from stdin, outputing to stdout:

#!/usr/bin/sh

N=0
SAVE=""
cat - | while read X
do
if [ $((${N} % 2)) -eq 0 ]
then
SAVE=${X}
else
echo "${SAVE} ${X}"
fi
N=$((${N} + 1))
done
exit 0

Clay
If it ain't broke, I can fix that.
David Lodge
Trusted Contributor

Re: Scripting help, joining two lines

Too complex (for pure shell) :-) try the following:

while read line
do
read line2
print "${line}${line2}"
done
So, can anybody make a shorter version using just builitins?

dave
Belinda Dermody
Super Advisor

Re: Scripting help, joining two lines

Ok Gentlemen let's not bicker, all answers are appreciated, I was currently using the read statement, but just wanted to reduce lines and characters within my script for ease of understanding. I would rather have one line of code in place of 6-7.