0

In my stats.txt page I have the following:

Get-VMHardDiskDrive | Select-Object Path

ComputerName : ACD-VMH04
Path         : D:\HYPER-V\VMDEV01\Virtual Hard Disks\f9314d7d-5d2d-11e0-8feb-806e6f6e6963_2012-06-29T153327.vhd
VhdFormat    : VHD
VhdType      : Dynamic
Used Space   : .07
Prov Space   : 4.00

ComputerName : ACD-VMH04
Path         : D:\HYPER-V\VMDEV01\Virtual Hard Disks\C_2012-06-29T153327.vhd
VhdFormat    : VHD
VhdType      : Dynamic
Used Space   : 258.04
Prov Space   : 906.34

I run the following AWK command to give me this:

ACD-VMH04
D:\HYPER-V\VMDEV01\Virtual Hard Disks\f9314d7d-5d2d-11e0-8feb-806e6f6e6963_2012-06-29T153327.vhd
VHD
Dynamic
.07
4.00

ACD-VMH04
D:\HYPER-V\VMDEV01\Virtual Hard Disks\C_2012-06-29T153327.vhd
VHD
Dynamic
258.04
906.34

The file has about 6 items like that however other files have more so I am wondering how to get the output to look like this:

ACD-VMH04 - D:\HYPER-V\VMDEV01\Virtual Hard Disks\f9314d7d-5d2d-11e0-8feb-806e6f6e6963_2012-06-29T153327.vhd - VHD - Dynamic - .07 - 4.00
ACD-VMH04 - D:\HYPER-V\VMDEV01\Virtual Hard Disks\C_2012-06-29T153327.vhd - VHD - Dynamic - 258.04 - 906.34

This will somewhat do the job however I do not know how to tell it stop and make a new line when it hits a blank line.

awk -F  " : " '{ ORS = " " } /Select-Object Path/ { output = 1; start = NR + 2 }; output && NR >= start { print $2, "-" }' stats.txt
2

I don't have a one liner for you, but the key concept here is to store the field until you have collected them all, then print them on one line. Also a blank line will have the number of fields (NF) equal to zero.

Code:

#!/bin/awk -f
BEGIN {FS = " : "; OFS = " - "}
NF > 0 {
    gsub(/[ ]+$/, "", $1)
    a[$1] = $2
}

NF == 0 {dump()}

END {dump()}

function dump() {
    print a["ComputerName"], a["Path"], a["VhdFormat"], a["VhdType"]
}

Results:

ACD-VMH04 - D:\HYPER-V\VMDEV01\Virtual Hard Disks\f9314d7d-5d2d-11e0-8feb-806e6f6e6963_2012-06-29T153327.vhd - VHD - Dynamic
ACD-VMH04 - D:\HYPER-V\VMDEV01\Virtual Hard Disks\C_2012-06-29T153327.vhd - VHD - Dynamic
1
perl -lne '
   /Select-Object Path/ and !$a++ and <>,next;

   /^ComputerName\s+:/ && $a .. /^$/ || eof and do{
      push  @A, (/\s+:\s+\K(.*)/)[0]          if /^ComputerName\s+:/ || /./;
      print join(" - ", splice(@A,0,@A)),"\n" if /^$/                || eof;
   };

' stats.txt

Output

ACD-VMH04 - D:\HYPER-V\VMDEV01\Virtual Hard Disks\f9314d7d-5d2d-11e0-8feb-806e6f6e6963_2012-06-29T153327.vhd - VHD - Dynamic - .07 - 4.00

ACD-VMH05 - D:\HYPER-V\VMDEV01\Virtual Hard Disks\C_2012-06-29T153327.vhd - VHD - Dynamic - 258.04 - 906.34
0

We can use " : " as delimter and print 2nd field of every line in awk


awk -v FS=" : " -v ORS="" '{{print $2,"- "}; if ( $0 ~ /^$/) {print "\n"}}' stats.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.