Friday 17 February 2017

Perl script to calculate total storage allocated to a Linux server

In a previous article  I created a small shell script to calculate the total disk space allocated to a Linux server. I used the lsblk command to gather the disk sizes.

In this article I'd like to accomplish the same task via perl.

This is mainly to demonstrate  how we can accommodate perl arrays and regular expressions to accomplish a task which would require the use of awk in case we were using bash shell.

So, here is the perl program I wrote:

#!/usr/bin/perl -w
#
use strict;
use Data::Dumper;

$|=1;

my @lsblk = `lsblk` ;
my $disk_total = 0;

 foreach (@lsblk) {
        chomp;

        if ($_ =~ m|\w* #match 0 or more alphanumeric characters
                    \s* #match 0 or more spcaces
                    disk #match the word disk
                    \s* # match 0 or more spaces after the word disk
                    |sigx)
                {

                my @out = split /\s+/, $_;
                $out[3] =~ /(\d*)G/sig ;
                print "disk $out[0] is of size $1 GB \n";
                $disk_total+=$1;
                }

        }

        print "total disk space allocated is $disk_total GB \n";


The execution of the program gave the following output:

[root@alive ~]# ./sum.pl
disk sda is of size 20 GB
disk sdb is of size 2 GB
total disk space allocated is 22 GB

Something interesting in the program is the presence of comments and white spaces within the regular expression. This is accomplished by adding the x option at the end of the regular expression.
In m| | the m character stands for match and is used to enclose the regular expression. We needed to mention m because we did not use the default regular expression enclosures which are two forward slashes (/ /).

Among the remaining options:
  • s allows matching across new lines 
  • i allows case insensitive matches  
  • g allows global matches.

No comments:

Post a Comment

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...