我想搜索文件中每行的花括号之间的值 并用。替换相应的值 0x0(例如1 - > 0x01,7 - > 0x07)
最初我正在使用正则表达式进行检查(/ {(。*?)} /这个正则表达式能够搜索{}括号内的所有值。 输入数据:
abc_def xxxx { 0} xxx
my_new_type new{ 0} my_new_type
c++_programming MY_NPYR{ 1} c++_programming
cprogramming ABCCDDDDRRRRTTTT { 2} cprogramming
perlbook NEW{ 7} xxxxx
代码:
#!/usr/bin/perl
use strict;
use warnings;
my $file = 'input.txt';
open my $fh, "<", $file or die "Couldn't open input file: $!";
while (<$fh>)
{
if (/{(.0?)}/)
{
s/0/0x00/;
}
elsif (/{(.1?)}/)
{
s/1/0x01/;
}
elsif (/{(.2?)}/)
{
s/2/0x02/;
}
elsif (/{(.7?)}/)
{
s/7/0x07/;
}
}
任何有关解释的帮助都会很感激。
答案 0 :(得分:0)
将其另存为script.pl
并将其调用为$ perl script.pl input.txt
:
use strict;
use warnings;
while (<>) {
s/\{ (\d+)\}/sprintf('{ 0x%02x}', $1)/ge;
print;
}
e
regex modifier将右侧评估为表达式。