如何使用 awk 将 3 个模式连接成一行

How to join 3 patterns as a line with awk

我在文件中得到了与此类似的文本。

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>

我只想为每个输出选择 "User-Friendly Name"、"Size" 和 "Name" 行(每个 "show")并像这样加入它们。

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

其实如果能得到就更好了:

200173800eeec23aa Production LUN 16.03

我试过了,但出于某种原因,它在每行之间添加了一个 \n,而不是在 3 种模式的末尾:

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

所以我实际上得到了(包括那个奇怪的标识):

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

我该如何解决这个问题?非常感谢。

这是适合您情况的 awk 脚本:

script.awk:

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

awk -f script.awk yourfile一样使用它。

输出说明:每一行都匹配自身。 例如,包含 Size 的行与原始 awk 脚本中的第二个括号匹配。 该行仅包含 "Size (GiB)...":因此:

  • a[1]a[3] 为空
  • a[2]整行(由于.*
  • 换行符是 printf
  • 中的 \n

只需删除每行末尾的'\n':gsub(/[\n]$/, "", $0)

惯用的 awk 方法:

$ awk -F' = ' '
   { gsub(/^ +| +\([^)]+\)$/,"",); m[]= }
   NR>1 && /^OVM/{ print m["User-Friendly Name"], m["Name"], m["Size"] }
' file
200173800eeec23ff OVM_SYS_REPO_PART_12346579123456789123456789 503.37
200173800eeec23aa Production LUN 16.03