JavaRed JavaRed - 1 year ago 81
Bash Question

Reformat a long file using awk/sed

I have a very long file. The contents of the file are like:

myserver1
kernel_version
os

myserver2
kernel_version
os

myserver3
kernel_version
os
...


There are more than 10.000 entries and 3 entries for each host. Hostname, kernel_version and OS version.

I would like to have an output like:

myserver1, kernel_version, os
myserver2, kernel_version, os
myserver3, kernel_version, os
...


instead. So what is the best awk/sed command to provide this output?

Answer Source

With sed:

$ sed '/^$/d;N;N;s/\n/, /g' infile                                  
myserver1, kernel_version, os                              
myserver2, kernel_version, os                              
myserver3, kernel_version, os

This works as follows:

/^$/d       # Delete line if empty (skips rest of commands)
N           # Append second line to pattern space
N           # Append third line to pattern space
s/\n/, /g   # Replace newlines by comma and a blank

If you want the criterion for the line to be skipped not be "empty line" but its line number (4, 8, 12...), you can replace the first command (this is a GNU extension):

sed '4~4d;N;N;s/\n/, /g' infile
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download