我有一个像这样(如下)的表结构形式的日志文件,我想编辑其中的相同发送 ID 列。我是 perl 的新手,尝试过但无法得到我想要的东西。
Code send_id dest_id
AW 96 45
BX 65 96
现在我必须将 send_id 列 ID 编辑为名称(如 96 = Alex 和 65 = James)并重新生成日志文件,如以下格式[在此处输入图像描述][2]。
Code send_id dest_id
AW Alex 45
BX James 96
我一直到这里,但没有得到所需的输出。我正在逐行阅读。 我越来越像了
Code send_id dest_id
AW Alex 45
James
谁能告诉我怎么做?
谢谢。
#!/usr/bin/perl
use warnings;
use strict;
my $log_file = "/home/ajay/Desktop/log.log";
open(Log1,"<$log_file") or die ("Could not open");
open(Log2,">$log2.pl");
while ($a=<Log1>) {
if ($a =~ /65/){
$a = "James";
print Log2"$a\n";
}
else {
print Log2"$a";
}
}
close Log2;
close Log1;
最佳答案
您可以使用以下方法替换当前行中的替换值:
while (my $line = <$Log1>) {
chomp $line;
if ($line =~ /65/){
$line =~ s/65/James/;
}
say $Log2 $line;
}
但是,更好的方法是保留不同替换值的哈希值。例如像这样:
use 5.22.0;
use strict;
use warnings;
use experimental qw(refaliasing);
my $log_file = "/home/ajay/Desktop/log.log";
my $log2_file = "/home/ajay/Desktop/log2.log";
open( my $Log1, "<", $log_file ) or die "Could not open file $log_file: $!";
open ( my $Log2, ">", $log2_file) or die "Could not open file $log2_file: $!";
while (my $line = <$Log1>) {
my @fields = split " ", $line;
next if @fields != 3;
\my $id = \$fields[1];
if ( exists $id_map{$id} ) {
$id = $id_map{$id};
}
say $Log2 (join "\t", @fields);
}
close $Log2;
close $Log1;
更新:
要使输出字段居中,您可以尝试:
my %id_map = ("65" => "James", "96" => "Alex");
open( my $Log1, "<", $log_file ) or die "Could not open file $log_file: $!";
my $field_width = 20;
my $num_fields = 3;
open ( my $Log2, ">", $log2_file) or die "Could not open file $log2_file: $!";
my $sep_line = ("-" x ($num_fields * $field_width));
while (my $line = <$Log1>) {
my @fields = split " ", $line;
next if @fields != $num_fields;
\my $id = \$fields[1];
if ( exists $id_map{$id} ) {
$id = $id_map{$id};
}
say $Log2 $sep_line if $. == 1;
say $Log2 (join " ", map {align($_, $field_width)} @fields);
say $Log2 $sep_line if $. == 1;
}
close $Log2;
close $Log1;
sub align {
my ( $str, $field_width ) = @_;
my $len = length $str;
if ($len >= $field_width) {
return $str;
}
else {
my $left = int(($field_width - $len) / 2);
my $right = $field_width - $left - $len;
my $str = (" " x $left) . $str . ( " " x $right );
return $str;
}
}
输出:
------------------------------------------------------------
Code send_id dest_id
------------------------------------------------------------
AW Alex 45
BX James 96
https://stackoverflow.com/questions/63822887/
相关文章:
typescript - Deno 记录器 FileHandler 不写入文件
javascript - Sonarqube 不显示安全热点
.net - Visual Studio 调试时未找到 : ScriptLoggingBuilder
python - 使用 Enterprise Architect Python API 旋转标签
javascript - 使用 Typescript 允许 React 组件上的任意数据-* 属性
amazon-web-services - 如何在本地运行和测试Cloud-init?
asp.net-core - 客户端中的 IdentityServer 4 身份验证事件