在 shell 脚本中格式化数据

在 shell 脚本中格式化数据
cat <file1>
name=HOST2
WWN=50.01.43.80.29.6A.84.82
WWN=50.01.43.80.29.6A.84.89
WWN=50.01.43.80.29.6A.84.8A
objectID=LU.R800.57488.43
objectID=LU.R800.57488.44
objectID=LU.R800.57489.44
name=HOST3
WWN=50.01.43.80.28.55.99.5C
WWN=50.01.43.80.28.55.99.5D
objectID=LU.R800.57488.45
objectID=LU.R800.57488.46
objectID=LU.R800.57488.47
objectID=LU.R800.5748A.47
name=HOST2
WWN=50.01.43.80.29.6A.84.87
WWN=50.01.43.80.29.6A.84.88
objectID=LU.R800.57486.41
objectID=LU.R800.57486.42
objectID=LU.R800.57486.43

我需要这样的输出。

HOST2 50.01.43.80.29.6A.84.82 LU.R800.57488.43
HOST2 50.01.43.80.29.6A.84.82 LU.R800.57488.44
HOST2 50.01.43.80.29.6A.84.82 LU.R800.57489.44
HOST2 50.01.43.80.29.6A.84.89 LU.R800.57488.43
HOST2 50.01.43.80.29.6A.84.89 LU.R800.57488.44
HOST2 50.01.43.80.29.6A.84.89 LU.R800.57489.44
HOST2 50.01.43.80.29.6A.84.8A LU.R800.57488.43
HOST2 50.01.43.80.29.6A.84.8A LU.R800.57488.44
HOST2 50.01.43.80.29.6A.84.8A LU.R800.57489.44
HOST3 50.01.43.80.28.55.99.5C LU.R800.57488.45
HOST3 50.01.43.80.28.55.99.5C LU.R800.57488.46
HOST3 50.01.43.80.28.55.99.5C LU.R800.57488.47
HOST3 50.01.43.80.28.55.99.5C LU.R800.5748A.47
HOST3 50.01.43.80.28.55.99.5D LU.R800.57488.45
HOST3 50.01.43.80.28.55.99.5D LU.R800.57488.46
HOST3 50.01.43.80.28.55.99.5D LU.R800.57488.47
HOST3 50.01.43.80.28.55.99.5D LU.R800.5748A.47
HOST2 50.01.43.80.29.6A.84.87 LU.R800.57486.41
HOST2 50.01.43.80.29.6A.84.87 LU.R800.57486.42
HOST2 50.01.43.80.29.6A.84.87 LU.R800.57486.43
HOST2 50.01.43.80.29.6A.84.88 LU.R800.57486.41
HOST2 50.01.43.80.29.6A.84.88 LU.R800.57486.42
HOST2 50.01.43.80.29.6A.84.88 LU.R800.57486.43

答案1

awk版本:

#!/usr/bin/awk -f

function output(name,WWN,objectID) {
  for (x in WWN) {
    for (y in objectID) {
      print name, x, y;
    }
  }
}

BEGIN {
  FS = "=";
}

{
  if ($1=="name") {
    output(name,WWN,objectID);
    name = $2;
    delete WWN;
    delete objectID;
  }
  if ($1=="WWN") {WWN[$2]=$2}
  if ($1=="objectID") {objectID[$2]=$2}
}

END {output(name,WWN,objectID)}

答案2

这是一个简单的 Perl 脚本:

#!/usr/bin/perl -n
#

sub printall {
    foreach my $wwn (@wwns) {
        foreach my $obj (@objects) {
            print "$name $wwn $obj\n";
        }
    }
}

if (/name=(.*)/) {
    if ($name) {
        printall;
    }
    $name = $1;
    @wwns = ();
    @objects = ();
} elsif (/WWN=(.*)/) {
    push @wwns, $1;
} elsif (/objectID=(.*)/) {
    push @objects, $1;
}

END {
    printall;
}

它循环遍历文件中的行,收集WWNs 和objectIds。然后,每次遇到name=文件末尾的行时,它都会按照示例的顺序打印所收集的内容。

相关内容