Perl初学者:如何在文件中查找/替换ascii字符?

Perl初学者:如何在文件中查找/替换ascii字符?,perl,replace,find,ascii,Perl,Replace,Find,Ascii,我对Perl完全陌生,我认为它是解决我的简单任务的最好语言。我需要将二进制文件转换为可读文件,并需要查找字符串,如\x00\x39并将其替换为\x09(tab)或类似内容 从bash开始,我从以下内容开始,它非常有效: perl -pi -e 's/abc/123/g' test.txt 但是,当我开始输入ascii码时,我会迷路: perl -pi -e 's/0x49/*/g' test.txt perl -pi -e 's/{char(49)}/*/g' test.txt 这个命令作为

我对Perl完全陌生,我认为它是解决我的简单任务的最好语言。我需要将二进制文件转换为可读文件,并需要查找字符串,如
\x00\x39
并将其替换为
\x09
(tab)或类似内容

从bash开始,我从以下内容开始,它非常有效:

perl -pi -e 's/abc/123/g' test.txt
但是,当我开始输入ascii码时,我会迷路:

perl -pi -e 's/0x49/*/g' test.txt
perl -pi -e 's/{char(49)}/*/g' test.txt
这个命令作为perl脚本中的一行看起来如何?我有大约几百个这样的查找/替换操作和一个500MB的文本文件。有什么需要我知道的警告吗

非常感谢你的帮助

Gary

使用
\x##
符号:

perl -pi~ -e 's/\x00/*/g' test.txt
要用括号中的代码替换每个“特殊”字符,请使用
/e
选项:

perl -pi~ -e 's/([\x0-\x09\x11-\x1f])/"[" . ord($1) . "]"/eg' test.txt

虽然在二进制文件上进行字符串替换有点奇怪,但下面介绍如何使用txt文件进行替换:

use strict;
use warnings;
use Tie::File;

my @file;
tie @file, 'Tie::File', 'test.txt' or die $!;

foreach (@file) {
  # your regexes go here
  s/abc/123/g;
  s/\0x49/*/g;
}

untie @file;
(来自Perl内核)允许您通过数组访问文件的行。更改将立即保存到文件中。在
foreach
循环中,逐行处理文件。这些行进入了
$\uu
,我们看不到。默认情况下,regex操作也应用于
$\uuu
,因此无需写下它



然而,我相信你走错了方向。在大多数情况下,您将无法逐行读取文件。作为起点参考。恐怕处理二进制文件要比文本处理复杂得多。

哇,非常感谢。我知道这并不像我想象的那么容易。哇,Perl真的很复杂;-)

这是我想到的。我希望这能帮助别人

顺便说一句:如果你有机会知道这是否也适用于Windows Perl,请告诉我

再次感谢

加里

#/usr/bin/perl
严格使用;
使用警告;
my$infle='/Users/gc/Desktop/a.bin';
我的$outfile='/Users/gc/Desktop/b.txt'#输入和输出可以是同一个文件;文件已存在时将被覆盖
my$data=读取文件($infle);
#第一批
$data=~s/0\x01J[\x00-\x19]/\x09AnythingYouWant\x09/g;
$data=~s/0\x00[\x00-\x19]/\x09AnythingYouWant\x09/g;
#第二批
$data=~s/\r/\x06/g;#CR进入\x06
$data=~s/\n/\x06/g;#LF进入\x06
$data=~s/\r\n/\x06/g;#CR LF进入\x06
# …
写入文件($outfile,$data);
出口
子读取文件{
我的($infle)=@;
打开我的$in、、$outfile或die“无法打开“$outfile”以写入$!”;;
打印$out$内容;
收尾美元;
返回;
}

是的,这正是我所需要的;我错过了反斜杠:-)
#!/usr/bin/perl

use strict;
use warnings;

my $infile = '/Users/gc/Desktop/a.bin'; 
my $outfile = '/Users/gc/Desktop/b.txt';    # in and out can be the same file; file will be overwritten when it already exists

my $data = read_file($infile);

# 1st batch
$data =~ s/0\x01J[\x00-\x19]/\x09AnythingYouWant\x09/g;
$data =~ s/0\x00[\x00-\x19]/\x09AnythingYouWant\x09/g;

# 2nd batch
$data =~ s/\r/\x06/g;                                   # CR into \x06
$data =~ s/\n/\x06/g;                                   # LF into \x06
$data =~ s/\r\n/\x06/g;                                 # CR LF into \x06

# …

write_file($outfile, $data);
exit;

sub read_file {
    my ($infile) = @_;

    open my $in, '<', $infile or die "Could not open '$infile' for reading $!";
    local $/ = undef;
    my $all = <$in>;
    close $in;

    return $all;
}

sub write_file {
    my ($outfile, $content) = @_;

    open my $out, '>', $outfile or die "Could not open '$outfile' for writing $!";;
    print $out $content;
    close $out;

    return;
}