如何将输出格式化为列?

时间:2012-11-10 16:15:19

标签: linux perl scripting output

如何修改以下脚本,使其在相应的列中显示每个值: 脚本的主体如下所示:

( $vmdisk, $totalio, $readpercentage, $cachehitpercentage, $currentkbpersecond,
  $maximumkbpersecond, $currentiopersecond, $maximumiopersecond
) = split (",", $line);
$totalio =~ s/\"//g;
$readpercentage =~ s/\"//g;
$cachehitpercentage =~ s/\"//g;
$currentkbpersecond =~ s/\"//g;
$maximumkbpersecond =~ s/\"//g;
$currentiopersecond =~ s/\"//g;
$maximumiopersecond =~ s/\"//g;

print "totalio:$totalio readpercentage:$readpercentage cachehitpercentage:$cachehitpercentage currentkbpersecond:$currentkbpersecond maximumkbpersecond:$maximumkbpersecond currentiopersecond:$currentiopersecond maximumiopersecond:$maximumiopersecond";

这将显示此类型的格式化输出:

totalio:75.0 readpercentage:20.0 cachehitpercentage:93.3 currentkbpersecond:33.8 maximumkbpersecond:33.8 currentiopersecond:15.0 maximumiopersecond:15.0

一切都在一条线上。我的目标是将输出放入列中并使其更具可读性。例如:

totalio readpercentage cachehitpercentage

75.00 20.0 93.0

我该怎么做?

4 个答案:

答案 0 :(得分:4)

    printf "%-10s %-10s %-10s\n", $totalio, $readpercentage, $cachehitpercentage; 

printf "%-10s %-10s %-10s\n", $totalio, $readpercentage, $cachehitpercentage;

应该做你想要的。只需根据需要根据模式附加变量。参考:printf

答案 1 :(得分:1)

对不起,我只是走出门,或者我会举一个更好的例子。你要找的东西是formats。阅读更多perldoc perlform

答案 2 :(得分:1)

如果您多次进行这些测量并打印到stdout或日志文件,则需要考虑格式。 perldoc perlform

$line = "0.0,75.0,20.0,93.3,33.8,33.8,15.0,15.0";

( $vmdisk, $totalio, $readpercentage, $cachehitpercentage, $currentkbpersecond, $maximumkbpersecond, $currentiopersecond, $maximumiopersecond) = split (",", $line);

$totalio =~ s/\"//g;
$readpercentage =~ s/\"//g;
$cachehitpercentage =~ s/\"//g;
$currentkbpersecond =~ s/\"//g;
$maximumkbpersecond =~ s/\"//g;
$currentiopersecond =~ s/\"//g;
$maximumiopersecond =~ s/\"//g;

format REPORT_HEADER = 
-------------------------------------------------------------------------------------------------------
Total IO     Read %     Cache Hit %     Current kB/sec     Max kB/sec     Current IO/sec     Max IO/sec
-------------------------------------------------------------------------------------------------------
.

format REPORT_BODY = 
 @####.#    @###.##         @###.##            @###.##        @###.##            @###.##        @###.##
$totalio, $readpercentage, $cachehitpercentage, $currentkbpersecond, $maximumkbpersecond, $currentiopersecond, $maximumiopersecond
.

select(STDOUT);

$~= "REPORT_HEADER";
write;

$~= "REPORT_BODY";
write;

会给你这样的输出:

-------------------------------------------------------------------------------------------------------
Total IO     Read %     Cache Hit %     Current kB/sec     Mac kB/sec     Current IO/sec     Max IO/sec
-------------------------------------------------------------------------------------------------------
    75.0      20.00           93.30              33.80          33.80              15.00          15.00

答案 3 :(得分:0)

在其他人中,还有方便的花花公子Text::Table