我正在嘗試使用 Perl 腳本決議下面的文本檔案 (test.txt) 以獲得底部提到的輸出格式(bugid、描述和用戶名)。你能幫我實作嗎?
test.txt 中的資料
(1111) user1 <[email protected]> 112111: description1 - some dummy string
(6473) user2 <[email protected]> 112112: description2 - some test string
(1999) user3 <[email protected]> 129119: description3 - some tes3 string
(3975) user3 <[email protected]> 196234: description4 - some tes4 string
這是我正在嘗試的腳本。
#!perl -w
#use strict;
no warnings;
my $ActivityLog = "test.txt";
my $ActListLog = "test3.txt";
open(FILE, "<$ActivityLog");
@prelist = <FILE>;
close (FILE);
foreach (@prelist)
{
if ($_ !~ /Bring over:/)
{
@postlist = split(".com> ", $_);
push (@result, $postlist[1]);
}
}
unlink $ActListLog;
open(LISTNAME,">$ActListLog")||die("cannot open the Input file");
print LISTNAME @result;
close LISTNAME;
所需輸出:
112111: description1 user1
112112: description2 user2
129119: description3 user3
196234: description4 user3
uj5u.com熱心網友回復:
如果用戶和描述沒有空格,如您的示例資料:
#!/usr/bin/perl
use strict;
use warnings;
my $ActivityLog = 'test.txt';
open my $fh,'<', $ActivityLog or die "$ActivityLog: $!";
while(<$fh>) {
print "$2 $3 $1\n" if(/^\S (\S ) \S (\d :) (\S )/);
# user number description
}
close $fh;
如果用戶和資料中可以有空格:
#!/usr/bin/perl
use strict;
use warnings;
my $ActivityLog = 'test.txt';
open my $fh,'<', $ActivityLog or die "$ActivityLog: $!";
while(<$fh>) {
print "$2 $3 $1\n" if(/^\(\d \)\s (.*)\s <\S ?>\s (\d :)\s (.*?)\s -/);
# user number description
}
close $fh;
uj5u.com熱心網友回復:
您可以在空白處拆分并保留您需要的 3 個專案。然后按所需順序列印出來:
use warnings;
use strict;
while (<DATA>) {
my (undef, $user, undef, $id, $desc) = split;
print "$id $desc $user\n";
}
__DATA__
(1111) user1 <[email protected]> 112111: description1 - some dummy string
(6473) user2 <[email protected]> 112112: description2 - some test string
(1999) user3 <[email protected]> 129119: description3 - some tes3 string
(3975) user3 <[email protected]> 196234: description4 - some tes4 string
印刷:
112111: description1 user1
112112: description2 user2
129119: description3 user3
196234: description4 user3
uj5u.com熱心網友回復:
使用這個 Perl 單行:
perl -lne '( $username, $bugid, $description ) = m{ < (\S ) @ \S \s (\S :) \s (\S ) }xms; print join " ", $bugid, $description, $username;' test.txt > test3.txt
Perl 單行使用這些命令列標志:
-e: 告訴 Perl 查找內嵌代碼,而不是在檔案中。
-n: 一次回圈輸入一行,$_默認分配給它。
-l:"\n"在執行行內代碼之前去除輸入行分隔符(默認情況下在 *NIX 上),并在列印時附加它。
正則運算式使用此修飾符:
/x: 忽略空格和注釋,以提高可讀性。
還請參見
perldoc perlrun::如何執行 Perl 解釋器:命令列開關
perldoc perlre:Perl 正則運算式(regexes)
perldoc perlre:Perl 正則運算式(regexes):量詞;字符類和其他特殊轉義;斷言;捕獲組
perldoc perlrequick:Perl 正則運算式快速入門
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/316258.html
標籤:perl
上一篇:如何理解Perl腳本
