如何在 perl 或 unix 脚本中第一次匹配某些条件时将一个十六进制文件拆分为两个十六进制文件

如何在 perl 或 unix 脚本中第一次匹配某些条件时将一个十六进制文件拆分为两个十六进制文件

我有一个包含以下内容的 HEX 文件,我想根据地址将它们拆分为两个 HEX 文件:

file_in.hex
@00000000
00 FC 00 20 89 01 00 00 D9 01 00 00 DB 01 00 00
DD 01 00 00 DF 01 00 00 E1 01 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 E3 01 00 00
43 00 00 00 10 00 00 20 00 00 00 00
@200005FC
18 FB FF 7F 01 00 00 00
@20000604
00 00 00 00 80 F0 FA 02 80 F0 FA 02 00 00 00
00 00 00 00 00 FC 02 00 20 64 03 00 20 CC 03 00 20

如果地址等于或大于@20000000,则其余的 HEX 将保存到第二个 HEX 文件中,因此结果应该是这样的:

file_out1.hex
@00000000
00 FC 00 20 89 01 00 00 D9 01 00 00 DB 01 00 00
DD 01 00 00 DF 01 00 00 E1 01 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 E3 01 00 00
43 00 00 00 10 00 00 20 00 00 00 00

file_out2.hex
@200005FC
18 FB FF 7F 01 00 00 00
@20000604
00 00 00 00 80 F0 FA 02 80 F0 FA 02 00 00 00 00
00 00 00 00 FC 02 00 20 64 03 00 20 CC 03 00 20

我对 perl 还很陌生。我可以使用“split”来做这件事吗?还是我必须使用循环来完成这项工作?awk 或 gawk 做这件事更容易吗?

答案1

这不太美观也不太可靠,但应该能完成工作。它确实假设地址只向上移动,并且实际上位于文本文件中,如 所示@

use strict;
use warnings;

my $input = 'file_in.hex';
my $output1 = 'file_out1.hex';
my $output2 = 'file_out2.hex';
my $flipped = 0;

open (my $fh, '<', $input);
open (my $oh, '>', $output1);

while(<$fh>){
    my $line = $_;
    if ($line =~ /[@]/ && !$flipped){
    my $numstr = $line;
    chomp $numstr;
    $numstr =~s/[@]//;
    if(hex($numstr) >= 0x20000000){
        $flipped = 1;
        close $oh;
        open ($oh, '>', $output2);
    }
    }

    print $oh $line;

}

close $oh;
close $fh;

答案2

试试这个 perl 脚本

#!usr/bin/perl

use strict;
use warnings;


$/ = "20 00 00 00 00";   # set input record separator
my $input = "/path/to/file";
my $i = 0;
open (my $fh, "<", $input);
while (<$fh>){
    my $filename = "$input$i";  #gen new filename
    open (OUT, ">$filename") or die "cannot create file $filename: $!"; #create and write to new file
    print OUT
    $i++;
}

相关内容