如何将3个模式作为一行与awk连接

时间:2016-05-05 21:44:40

标签: shell awk gawk

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

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>

我只想选择"用户友好名称","尺寸"和"姓名"每个输出的行(对于每个"显示")并像这样加入它们。

  

用户友好名称= 200173800eeec23aa名称=生产LUN大小(GiB)= 16.03

事实上,如果我能得到它会更好:

  

200173800eeec23aa Production LUN 16.03

我尝试了这个但是由于某种原因它在每一行之间粘贴\ n而不是在3种模式的末尾:

awk 'match($0, /(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

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

3 个答案:

答案 0 :(得分:3)

以下是适合您情况的awk脚本:

<强> script.awk:

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

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

输出说明:每行匹配本身。 例如,包含Size的行与原始awk脚本中的第二个括号匹配。 该行仅包含“Size(GiB)...”:所以:

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

答案 1 :(得分:0)

惯用的awk方法:

$ awk -F' = ' '
   { gsub(/^ +| +\([^)]+\)$/,"",$1); m[$1]=$2 }
   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

答案 2 :(得分:-1)

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