将三行集转置为列

将三行集转置为列

我有一个包含以下条目的文件:

[root@ovmm329 ovm_utils]# cat /tmp/disk.txt
Physical Disk : 'IBM (67) device=/dev/mapper/360050768018206483000000000000453 shareddisk=true
Physical Disk : 'IBM (58) device=/dev/mapper/36005076801820648300000000000043f shareddisk=true
Physical Disk : 'IBM (59) device=/dev/mapper/360050768018206483000000000000440 shareddisk=true
Physical Disk : 'IBM (71) device=/dev/mapper/360050768018206483000000000000497 shareddisk=true
[root@ovmm329 ovm_utils]#

我尝试以我所知道的所有可能方式使用 sed 和 awk,但无法以所需的格式获取它。我想要这种格式的文件:

Physical Disk  device                                          Shareddisk
IBM (67)        /dev/mapper/360050768018206483000000000000453  true
IBM (58)        /dev/mapper/36005076801820648300000000000043f  true
IBM (59)        /dev/mapper/360050768018206483000000000000440  true
IBM (71)        /dev/mapper/360050768018206483000000000000497  true

答案1

使用 awk 变量和多个匹配,您可以读取每一行,存储您需要的内容,然后打印最后一个匹配并重新开始。

#!/usr/bin/awk -f

BEGIN {
  DISK=""
  DEVICE=""
  FS=" : "
  print "Physical Disk\tdevice\t\t\t\t\t\tShareddisk"
  }

/Physical Disk/ {
  DISK=$2
  FS="="
}

/device/ {
  DEVICE=$2
}

/shareddisk/ {
  print DISK "\t" DEVICE "\t" $2
  FS=" : "
  }

然后针对您的文件运行脚本awk -f ./script.awk ./disk.txt

$ awk -f ./parse.awk ./disk.txt
Physical Disk   device                                          Shareddisk
'IBM (67)       /dev/mapper/360050768018206483000000000000453   true
'IBM (58)       /dev/mapper/36005076801820648300000000000043f   true
'IBM (59)       /dev/mapper/360050768018206483000000000000440   true
'IBM (71)       /dev/mapper/360050768018206483000000000000497   true

为了分解脚本,它从一个BEGIN在开始时运行的块开始。它定义了一些变量并设置字段分隔符FS并打印标题。第一个匹配用于Physical Disk并将磁盘名称存储到变量中。=由于设备和共享磁盘行使用,因此字段分隔符更改为=。当命中行匹配时/shareddisk/,将打印变量,并再次更改字段分隔符以匹配下一个物理磁盘行。

编辑

这假设文件的格式是:

cat disk.txt
Physical Disk : 'IBM (67)
  device=/dev/mapper/360050768018206483000000000000453
  shareddisk=true
Physical Disk : 'IBM (58)
  device=/dev/mapper/36005076801820648300000000000043f
  shareddisk=true
Physical Disk : 'IBM (59)
  device=/dev/mapper/360050768018206483000000000000440
  shareddisk=true
Physical Disk : 'IBM (71)
  device=/dev/mapper/360050768018206483000000000000497
  shareddisk=true

相关内容