簡體   English   中英

如何使用Perl格式格式化/ etc / passwd文件

[英]How to format /etc/passwd file using perl formatting

我正在嘗試使用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命令僅在終端內獲取用戶名時,它將顯示所有用戶名。 不過,它不會在腳本內部執行。

您沒有遍歷/ etc / passwd文件,而是將第一組字段返回到變量中,但僅使用第一組。 考慮一下:

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

而是使用以下腳本嘗試perl myscript.pl </ etc / 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中讀取每一行並分別進行處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM