Nocturn Nocturn - 6 months ago 22
Bash Question

How to join 3 patterns as a line with awk

Im got text similar to this one in a file.

OVM>
show PhysicalDisk id='12346579123456789123456789'
Data:
Page83 ID = OVM_SYS_REPO_PART_12346579123456789123456789
Server Reserved = No
Shareable = No
Size (GiB) = 503.37
State = UNKNOWN
Thin Provision = No
Type = LUN
User-Friendly Name = 200173800eeec23ff
Vendor = Lenovo
File System 1 = 12346579123456789123456789
Volume Group = 12346579123456789123456789 [Local Storage Volume Group]
Id = 12346579123456789123456789 [OVM_SYS_REPO_PART_12346579123456789123456789]
Name = OVM_SYS_REPO_PART_12346579123456789123456789
Locked = false
OVM>
show PhysicalDisk id='123465791234567891234567892'
Data:
Storage Targets 1 = 0x50017380eeec0140
Storage Targets 2 = 0x50017380eeec0170
Storage Targets 3 = 0x50017380eeec0150
Storage Targets 4 = 0x50017380eeec0172
Storage Targets 5 = 0x50017380eeec0152
Storage Targets 6 = 0x50017380eeec0182
Page83 ID = 200173800eeec23aa
Server Reserved = No
Shareable = Yes
Size (GiB) = 16.03
State = UNKNOWN
Thin Provision = Yes
Type = LUN
User-Friendly Name = 200173800eeec23aa
Vendor = IBM
File System 1 = 123465791234567891234567892 [Server Pool File System]
Volume Group = 123465791234567891234567892 [FibreChannel Volume Group]
Id = 123465791234567891234567892 [Production Quorum LUN]
Name = Production LUN
Locked = false
OVM>


I want to pick only the "User-Friendly Name", "Size" and "Name" lines for each output (for each "show") and join them like so.


User-Friendly Name = 200173800eeec23aa Name = Production LUN Size (GiB) = 16.03


In fact, it would be even better if I could get:


200173800eeec23aa Production LUN 16.03


I tried this but for some reason it sticks a \n between each line instead at the end of the 3 patterns:

awk 'match($0, /(User.*)|(Name.*)|(Size.*)/, a) {printf "%s %s %s\n", a[1], a[2], a[3]}' object_data/LUNs.txt


So I'm actually getting (including that weird identation):

User-Friendly Name = 200173800eeec23aa
Name = Production LUN
Size (GiB) = 16.03


How can I fix this? Thank you very much.

Answer

Here is an awk script for your situation:

script.awk:

BEGIN {FS="="}
$1 ~ "User-Friendly Name" { ufn = $2 }
$1 ~ "Size" { sz = $2 }
$1 ~ "Name" { printf("%s%s%s\n",ufn,$2, sz) }

Use it like awk -f script.awk yourfile.

Explanation for your output: Each line is matched for itself. For example the line containing Size is matched by the second parenthesis from your original awk script. The line contains only "Size (GiB)...": so:

  • a[1] and a[3] are empty
  • a[2] is the whole line (due to the .*)
  • the newline is the \n from the printf
Comments