49

With a simple bash script I generate a text file with many lines like this:

192.168.1.1
hostname1
192.168.1.2
hostname2
192.168.1.3
hostname3

Now I want to reformat this file so it looks like this:

192.168.1.1 hostname1
192.168.1.2 hostname2
192.168.1.3 hostname3

How would I reformat it this way? Perhaps sed?

icktoofay
  • 126,289
  • 21
  • 250
  • 231
fwaechter
  • 885
  • 3
  • 10
  • 19

3 Answers3

59
$ sed '$!N;s/\n/ /' infile
192.168.1.1 hostname1
192.168.1.2 hostname2
192.168.1.3 hostname3
Tim
  • 953
  • 7
  • 11
  • 1
    Would you please explain how it come to be? – NawaMan Oct 03 '09 at 14:57
  • 12
    @NawaMan: If you mean "how does it work?" then: If not (!) the last line ($) then append the next line (N) and replace the newline between them with a space (s/\n/ /) and repeat starting with the next line (which will be the 3rd, 5th, etc.). – Dennis Williamson Oct 03 '09 at 17:07
47

I love the simplicity of this solution

cat infile | paste -sd ' \n'

192.168.1.1 hostname1
192.168.1.2 hostname2
192.168.1.3 hostname3

or make it comma separated instead of space separated

cat infile | paste -sd ',\n'

and if your input file had a third line like timestamp

192.168.1.1
hostname1
14423289909
192.168.1.2
hostname2
14423289910
192.168.1.3
hostname3
14423289911

then the only change is to add another space in to the delimiter list

cat infile | paste -sd '  \n'

192.168.1.1 hostname1 14423289909
192.168.1.2 hostname2 14423289910
192.168.1.3 hostname3 14423289911
rob
  • 8,134
  • 8
  • 58
  • 68
39

Here's a shell-only alternative:

while read -r first; do read second; echo "$first $second"; done < filname

-r - Do not allow backslashes to escape any characters

HappyTown
  • 6,036
  • 8
  • 38
  • 51
Jukka Matilainen
  • 9,608
  • 1
  • 25
  • 19