我试图以三种不同的方式重现相同的结果,但在使用“使用Shell”时无法弄清楚如何使其工作(下面的方法2a),任何帮助?
#!/usr/bin/perl
# v5.10.1 / linux
use strict;
use warnings;
use Shell;
# method 1 start
my $result = `df -H | grep -vE '^Filesystem|tmpfs|cdrom|none' | awk '{ print \$5 "\t" \$1}'`;
print $result . "\n";
# end of method 1
# I would like to try to reproduce the above but by using "use Shell", even if the above is already somehow using such anyway?!
# method 2a start
my $result2 = df ("-H"); # use powers of 1000 not 1024 # human readable
print $result2 . "\n"; # I can only get it working up to here
# end 2a
# 2b)
# or use regexs on df -H's output
my @linesofoutput= $result2=~/(.*?)\n/g; # needs checking to see if I'm getting the lines right with this?!
foreach my $temp(@linesofoutput){
if (($temp =~ /^Filesystem/)||($temp =~ /^tmpfs/)||($temp =~ /^cdrom/)||($temp =~ /^none/)){
# do nothing for lines starting with Filesystem, tmpfs or cdrom or none
# print "Do not show: $temp\n";
}else{
#print "$temp\n"; # lines wanted
my @words = split(/\s/, $temp); # make an array out of each line, splitting on any whitespace character: space, tab, newline, etc
@words = grep(!/^$/, @words); # remove empty elements. check this(not starting with, ending with)???
print "$words[4]". "\t"."$words[0]"."\n"; # filesystem entries are in index0, size index1, used index2, avail 3...
# be careful of /path/name of file or folder... because of the gaps, and so they could be made up of multi indexs
}
}
# end of method 2b
答案 0 :(得分:2)
如果我理解正确,方法2a)应该将df -H
的输出传输到grep
,并且应该传递给awk
。简而言之:您希望完成方法1的完整重定向,这是由perl中隐式启动的shell完成的。
Shell
包将不帮助您。该软件包的唯一目的是,您可以轻松地调用一个命令。所以df("-H")
可以工作,但是全部都可以。
如果你想一想,那不是很大的损失:你需要的只是df
的输出。其余的是解析和处理输出 - 应该在perl中完成。所以方法2b无论如何都是更好的方法 - 如果你有点像这样:
my @lines = df("-H");
shift @lines; # get rid of "Filesystem..."
for( @lines ){
next if /^tmpfs|cdrom|none/;
my @words = split('\s+', $_);
print $words[4], "\t", $words[0], "\n";
}
我也可以提出一个方法3:用来自perl的东西替换对“df -H”的调用。以下是一些使用statfs(2)
或statvfs(2)
系统调用的CPAN模块: