重新格式化输出

时间:2017-06-15 04:09:32

标签: linux shell unix

我使用以下命令获取磁盘状态:

  

/ opt / Navisphere / bin / naviseccli -h VNX5500-1-1 getdisk -state

我得到的输出就像:

Bus 0 Enclosure 0  Disk 0

State:                   Enabled
Bus 0 Enclosure 0  Disk 2

State:                   Enabled
Bus 0 Enclosure 0  Disk 4

State:                   Enabled
Bus 0 Enclosure 0  Disk 6

State:                   Enabled
Bus 0 Enclosure 0  Disk 8

State:                   Enabled
Bus 0 Enclosure 0  Disk 10

State:                   Enabled
Bus 0 Enclosure 0  Disk 12

State:                   Enabled
Bus 0 Enclosure 0  Disk 14

State:                   Enabled
Bus 0 Enclosure 0  Disk 16

我正在尝试格式化输出以获得每条总线的一行。类似的东西:

Bus 0 Enclosure 0  Disk 0   [State: Enabled]
Bus 0 Enclosure 0  Disk 2   [State: Enabled]
..

1 个答案:

答案 0 :(得分:2)

使用awk

awk '/^Bus/ {a=$0}; /^State/ {print a" ["$1, $2"]"}' file.txt 
  • /^Bus/ {a=$0}:如果该行以Bus开头,请将行/记录另存为变量a

  • /^State/ {print a" ["$1, $2"]"}:如果该行以State开头,则保存以所需格式打印字段,其中a

示例:

% cat file.txt
Bus 0 Enclosure 0  Disk 0

State:                   Enabled
Bus 0 Enclosure 0  Disk 2

State:                   Enabled
Bus 0 Enclosure 0  Disk 4

State:                   Enabled
Bus 0 Enclosure 0  Disk 6

State:                   Enabled
Bus 0 Enclosure 0  Disk 8

State:                   Enabled
Bus 0 Enclosure 0  Disk 10

State:                   Enabled
Bus 0 Enclosure 0  Disk 12

State:                   Enabled
Bus 0 Enclosure 0  Disk 14

State:                   Enabled
Bus 0 Enclosure 0  Disk 16


% awk '/^Bus/ {a=$0}; /^State/ {print a" ["$1, $2"]"}' file.txt 
Bus 0 Enclosure 0  Disk 0 [State: Enabled]
Bus 0 Enclosure 0  Disk 2 [State: Enabled]
Bus 0 Enclosure 0  Disk 4 [State: Enabled]
Bus 0 Enclosure 0  Disk 6 [State: Enabled]
Bus 0 Enclosure 0  Disk 8 [State: Enabled]
Bus 0 Enclosure 0  Disk 10 [State: Enabled]
Bus 0 Enclosure 0  Disk 12 [State: Enabled]
Bus 0 Enclosure 0  Disk 14 [State: Enabled]