gpt4 book ai didi

regex - 珀尔 : Edit the log file data

转载 作者:行者123 更新时间:2023-12-05 07:01:28 25 4
gpt4 key购买 nike

我有一个像这样(如下)的表结构形式的日志文件,我想编辑其中的相同发送 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

关于regex - 珀尔 : Edit the log file data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63822887/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com