Convert rows to columns
If you have the rs
(reshape) utility available, you can do the following:
rs -Tzc: < input.txt
This gives the output format exactly as specified in the question, even down to the dynamic column widths.
-T
Transposes the input data-z
sizes the columns appropriately from the max in each column-c:
uses colon as the input field separator
This works for arbitrarily sized tables, e.g.:
$ echo "Name:Alice:Bob:Carol
Age:12:34:56
Eyecolour:Brown:Black:Blue" | rs -Tzc:
Name Age Eyecolour
Alice 12 Brown
Bob 34 Black
Carol 56 Blue
$
rs
is available by default on OS X (and likely other BSD machines). It can be installed on Ubuntu (and debian family) with:
sudo apt-get install rs
EDIT: Extensible to any number of output rows, in a simple one-liner for
loop:
for ((i=1;i<=2;i++)); do cut -d: -f "$i" input | paste -sd: ; done | column -t -s:
Original answer:
You can do this as a one-liner using bash
process substitution:
paste -sd: <(cut -d: -f1 input) <(cut -d: -f2 input) | column -t -s:
The -s
option to paste
makes it handle each file one at a time. The :
delimiter set in paste
is "caught" by the -s
option to column
at the end, to pretty up the format by making the fields line up.
The cut
commands in the two process substitutions pull out the first field and the second field, respectively.
Whether there are blank lines in the input or not doesn't matter, as column -t -s:
will clean up the output regardless. (There were blank lines in the original input specified in the question, but they've since been removed. The above command works regardless of blank lines.)
Input - contents of file named "input" in above command:
Virtual_Machine:OL6U7
ID:0004fb00000600003da8ce6948c441bd
Status:Running
Memory:65536
Uptime:17103
Server:MyOVS1.vmworld.com
Pool:HA-POOL
HA:false
VCPU:16
Type:Xen PVM
OS:Oracle Linux 6
Output:
Virtual_Machine ID Status Memory Uptime Server Pool HA VCPU Type OS
OL6U7 0004fb00000600003da8ce6948c441bd Running 65536 17103 MyOVS1.vmworld.com HA-POOL false 16 Xen PVM Oracle Linux 6
Using awk, store off the key and value and print them out in the end.
#!/usr/bin/awk -f
BEGIN {
CNT=0
FS=":"
}
{
HDR[CNT]=$1;
ENTRY[CNT]=$2;
CNT++;
}
END {
for (x = 0; x < CNT; x++)
printf "%s\t",HDR[x]
print""
for (x = 0; x < CNT; x++)
printf "%s\t",ENTRY[x]
}
The just run awk -f ./script.awk ./input.txt