需要使用 awk 进行格式化方面的帮助

需要使用 awk 进行格式化方面的帮助

输入数据

<Device>
      <dev_name>00002</dev_name>
      <Storage_Group>
        <Group_Info>
          <group_name>N/A</group_name>
    </Device>
    <Device>
      <dev_name>000BC</dev_name>
         <Storage_Group>
        <Group_Info>
          <group_name>sg_optimized</group_name>
          <group_name>sg_metro-nonir</group_name>
          <group_name>sh_m4i-pr-ixcem-a02</group_name>
          <group_name>sh_m4i-pr-ixcem-a01</group_name>
    </Device>
    <Device>
      <dev_name>000BD</dev_name>
          <group_name>sg_optimized</group_name>
         <dev_count>1</dev_count>
          <sg_count>0</sg_count>

          <group_name>sg_metro-nonir</group_name>
          <group_name>sh_m4i-pr-ixcem-b01</group_name>
          <group_name>sh_m4i-pr-ixcem-b02</group_name>
    </Device>
    <Device>
      <dev_name>000BE</dev_name>
          <group_name>sg_optimized</group_name>
    </Device>

输出

00002 N/A
000BC sg_optimized sg_metro-nonir sh_m4i-pr-ixcem-a02 sh_m4i-pr-ixcem-a01
000BD sg_optimized sg_metro-nonir sh_m4i-pr-ixcem-b01 sh_m4i-pr-ixcem-b02
000BE sg_optimized

我正在使用它,但它只打印最后一个组名。跳过之前的组名称。

VMAX_TDEV_SG_EXTRACT () {
cat $TMPLOGDIR/tdevsg.m4i-pr-llpmax-a01.map |awk '
function vmax_tdev_sg_extract(DEV_NAME,SG_NAME) {
        print DEV_NAME,SG_NAME;
}
BEGIN {
  FS = "[<>/]" ;
}
{
if ($0 ~ /dev_name>/) {
vmax_tdev_sg_extract(DEV_NAME,SG_NAME);
DEV_NAME = $3
SG_NAME=""
}
if ($0 ~ /\ygroup_name>\y/)  { SG_NAME=$3 }
}
END {vmax_tdev_sg_extract(DEV_NAME,SG_NAME)}
'
}

答案1

awk '
    BEGIN { FS="[<>]" }
    $2 == "dev_name"   { prt(); name = $3 }
    $2 == "group_name" { groups[++numGroups] = $3 }
    END { prt() }

    function prt(       i) {
        if ( name != "" ) {
            printf "%s%s", name, OFS
            for (i=1; i<=numGroups; i++) {
                printf "%s%s", groups[i], (i<numGroups ? OFS : ORS)
            }
            numGroups = 0
        }
    }
' file
00002 N/A
000BC sg_optimized sg_metro-nonir sh_m4i-pr-ixcem-a02 sh_m4i-pr-ixcem-a01
000BD sg_optimized sg_metro-nonir sh_m4i-pr-ixcem-b01 sh_m4i-pr-ixcem-b02
000BE sg_optimized

相关内容