Combine two lines

I have a file called test.txt. Inside this file is the following:

tcenh100.telkom.co.za
100.200.300.400

tcenh101.telkom.co.za
500.600.700.800

I want to take out the new lines and spaces, then I want to put the ip address of the host name next to the host name on the same line, as soon as this is done, I want to switch around the ip address and host name with a space between them. The file must look as follows after script is done running:

100.200.300.400 tcenh100.telkom.co.za
500.600.700.800 tcenh101.telkom.co.za

Anyone can help please?

Thanks
Wolf:confused:

#!/usr/bin/perl
while ($line = <>) {
    chomp ($line);

   if ($line ne "") {

     if ($line =~ m/telkom/) {
         $hold = $line;
     } else {
         print $line, " ";
         print $hold, "\n";
     }
   }
}

There you go! Save it in a file called "lineconvert", then run it like this:

lineconvert test.txt > outputfile

:smiley:

Dang! WIntellect beat me to the punch. Oh well, I'm gonna post my sed script anyway...

#! /usr/bin/sed -f
#
N         ;# suck in a second line
N         ;# suck in a third line
s/\n/ /g  ;# change new-line to space
s/  */ /g ;# change many spaces to one space
s/\([^ ]*\) \([^ ]*\)/\2 \1 / ;# swap the fields

Hey -

I liked this post - I got it on my lunch break at work; it proved to be a bit of fun! Sorta like doing the crossword in the newspaper - only better!

Can't stand crosswords!

:wink:

wolf wants to turn this:

tcenh100.telkom.co.za
100.200.300.400

tcenh101.telkom.co.za
500.600.700.800

into this:

100.200.300.400 tcenh100.telkom.co.za
500.600.700.800 tcenh101.telkom.co.za

Here are two versions, similar to WIntellect's but more concise:

#!/bin/awk

/telkom/                         { hold = $1 ; next}
/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/ { print $1 " " hold }

The concise perl version is similar:

#!/usr/bin/perl -lan
/telkom/          && do { $hold = $F[0]; next };
/\d+(?:\.\d+){3}/ && do { print $F[0], " ", $hold };

In both, the "next" is an efficicency hack and only needed if your file is really, really, really big.

Concise... <gasp> Perl code... <gasp> Hurt brain! :smiley:

:smiley: But it's about the same thing as the awk version, so an awk user can work it out from there.

How about a Bourne shell version, using expr. I have no idea how portable expr stuff is.

#!/bin/sh
while read word rest ; do
  if [ `expr "$word" : '.*\.telkom\.'` -gt 0 ] ; then
    hostname=$word
  elif [ `expr "$word" : '^[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*$'` -gt 0 ] ; then
    echo "$word $hostname"
  fi
done

The AWK solution is of course very simple and easy to read :wink:

awkit file:
/^[a-zA-Z]/{d=$1;next}
/^[0-9]/{print $1,d}

For each line starting with an alphabetic character, store it in variable d.
For each line starting with a numeric character, print it and varialble d.

awk -f awkit < test.txt
100.200.300.400 tcenh100.telkom.co.za
500.600.700.800 tcenh101.telkom.co.za

:stuck_out_tongue: