0

I try to get a specific output from a simple perl command en write it to a variable to use in a later stadium in my script.

I have to following code:

#!/usr/bin/perl

use strict;
use warnings;


my $serial = system("hdparm -I /dev/sda | grep 'Serial Number:'");
print $serial;

This generates the following output:

0root@spool-B-01:~# ./test.pl
    Serial Number:      9VS3D79X

But i need the output to be as followed:

0root@spool-B-01:~# ./test.pl
9VS3D79X

I have tried some things with awk and sed. But that won't give the output the way i need it.

For example:

#!/usr/bin/perl

use strict;
use warnings;
use Sys::Hostname;


my $serial = system("hdparm -I /dev/sda | grep 'Serial Number:' | sed -e 's/Serial Number://g'");
print $serial;

Show the output like:

0root@spool-B-01:~# ./test.pl
          9VS3D79X

It is almost correct but you still got the tabs before the serial code.

I hope that somebody can help me figure this stuff out and do it the correct way.

Mitchel
  • 117
  • 1
  • 4

3 Answers3

3

There are various ways to launch system commands from perl: system, exec, and backtic are the most popular choices. Some capture output, some don't. For a good rundown check this link: What's the difference between Perl's backticks, system, and exec?

In this case, however, backtick is most appropriate:

For example a quick script such as:

my $out = `ls`;
print "$out \n";

Will print out the results of ls to the screen.

In your case I would try:

my $command = "hdparm -I /dev/sda | grep 'Serial Number:' | sed -e 's/Serial Number://g'";

my $serial = `$command`;
print $serial;  #white space 

#Remove whitespace
$serial =~ s/^(\s+)//g;  

print $serial;  #No white space

I have a mac in front of me so I don't have access to the hdparm command

With regards to the whitespace removal \s is the white space character so the regex

s/^\s+//g;

translates to replace all white space starting from the start of the line with nothing

Community
  • 1
  • 1
Jeef
  • 26,861
  • 21
  • 78
  • 156
2
#!/usr/bin/perl

use strict;
use warnings;
use autodie;

open my $fh, '-|', 'hdparm -I /dev/sda';
while (<$fh>) {
    print "$_\n" if s/Serial Number://g;
}
close $fh
mpapec
  • 50,217
  • 8
  • 67
  • 127
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
-1

Try this:

#!/usr/bin/perl
use strict;
use warnings;

my @serial = `hdparm -I /dev/sda`;
foreach my $line (@serial) {
  print $1 if ($line =~ /(?:\s+)Serial Number:(?:\s+)(\w+)/);
}

Output:

root@spool-B-01:~# ./test.pl
9VS3D79X
Filippo Lauria
  • 1,965
  • 14
  • 20