【问题标题】:How to format /etc/passwd file using perl formatting如何使用 perl 格式化格式化 /etc/passwd 文件
【发布时间】:2017-11-16 06:50:49
【问题描述】:

我正在尝试使用 perl 格式化来格式化 /etc/passwd 文件

这是我目前想出的:

#!/usr/bin/perl

use warnings;

format MYFORMAT =
@<<<<<<<<<<<<<<<| @<<<<<<<<<<<<<<<| @<<<<<<<<<<<<<<<
$username,        $UID,             $name
.

$username = `cut -d: -f1 /etc/passwd`;
$UID = `cut -d: -f3 /etc/passwd`;
$name = `cut -d: -f5 /etc/passwd`;

$~ = "MYFORMAT";
write;

我没有收到任何警告或错误。格式化有效,但问题是,它只显示 etc/passwd 文件的第一行。我只得到 root、0 和 root 作为用户名、UID 和名称。

我需要为每列打印的所有用户名、UID 和名称。我不知道自己做错了什么,因为当我运行 bash 命令以仅获取终端内的用户名时,它会显示所有用户名。但它不会在脚本内部执行此操作。

【问题讨论】:

  • 我没有收到任何警告,我更改了代码的格式。

标签: bash shell perl


【解决方案1】:

您没有循环遍历 /etc/passwd 文件,而是将第一组字段返回到变量中,但随后仅使用第一组。考虑一下:

#!/usr/bin/perl
$username = `cut -d: -f1 /etc/passwd`;
print $username;

试试 perl myscript.pl /passwd 这个脚本:

#!/usr/bin/perl
use warnings;
use strict;
my $username;
my $UID;
my $name;

format =
@<<<<<<<<<<<<<<<| @<<<<<<<<<<<<<<<| @<<<<<<<<<<<<<<<
$username,        $UID,             $name
.

while (<>) {
    ($username, undef, $UID, undef, $name, undef) = split(':');
    write();
}

输出如下:

~/tmp$ perl t2.pl < /etc/passwd
root            | 0               | root
daemon          | 1               | daemon
bin             | 2               | bin
sys             | 3               | sys
sync            | 4               | sync
games           | 5               | games

如果您不给格式命名,则默认为 STDOUT。您可以从 /etc/passwd 读取每一行并单独处理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    • 2012-01-22
    • 2011-04-13
    • 1970-01-01
    • 1970-01-01
    • 2014-11-08
    • 1970-01-01
    相关资源
    最近更新 更多