Perl - 在 linux 上获取可用磁盘 space 使用情况

Perl - get free disk space usage on linux

我想知道如何从 df ("/") 中获取第二行第四列的​​值。这是 df:

的输出
Filesystem      Size  Used Avail Use% Mounted on
rootfs          208G  120G   78G  61% /
fakefs          208G  120G   78G  61% /root
fakefs          1.8T  1.3T  552G  70% /home4/user
fakefs          4.0G  1.3G  2.8G  31% /ramdisk/bin
fakefs          4.0G  1.3G  2.8G  31% /ramdisk/etc
fakefs          4.0G  1.3G  2.8G  31% /ramdisk/php
fakefs          208G  120G   78G  61% /var/lib
fakefs          208G  120G   78G  61% /var/lib/mysql
fakefs          208G  120G   78G  61% /var/log
fakefs          208G  120G   78G  61% /var/spool
fakefs          208G  120G   78G  61% /var/run
fakefs          4.0G  361M  3.7G   9% /var/tmp
fakefs          208G  120G   78G  61% /var/cache/man

我正在尝试使用我相当陌生的 perl 获取可用的免费 space (78GB)。我可以使用以下 linux 命令获取值,但我听说根本没有必要在 perl 中使用 awk,因为 perl 可以做 awk 本身可以做的事情。

df -h | tail -n +2 | sed -n '2p' | awk '{ print  }'

我很难过。我尝试使用 Filesys::df 模块,但是当我打印出可用的使用百分比时,它会给我一个与命令行中的 运行 df 不同的值。感谢帮助。

如果您希望在 perl 中完成所有操作,那么:

df -h | perl -e 'while (<stdin>) { if ($. == 2) { @x = split; print $x[3] }}'

这单独使用 perl 来读取 df -h 的输出,并且对于第二条记录 ($. == 2) 根据空格将记录拆分为字段,并输出字段 3 (从0开始计数)。

这似乎也能正常工作:

df -h | awk 'NR==2 {print }'

获取第二行并打印第四个字段。

再简洁一点:

df -h | perl -wlane 'print $F[3] if $. == 2;'


-w   enable warnings
-l   add newline to output(and chomps newline from input line)
-a   splits the fields on whitespace into the @F array, which you access using the syntax $F[n] (first column is at index position 0)
-n   puts the code inside the following loop:

    LINE:
        while (<>) { 
            ...     # code goes here
        }
     # <> reads lines from STDIN if no filenames are given on the command line

-e   execute the string
$.   current line number in the file (For the first line, $. is 1)