【发布时间】:2011-08-04 12:51:42
【问题描述】:
使用 Perl 单行正则表达式命令替换 INI 文件的特定部分中的值?
我想将“Margin Top”值 1 替换为 0。该部分必须是“[Pagebar Button Skin]”。
在 RegExr 中尝试使用 global 和 dotall 的 "(\[Pagebar Button Skin\].+?Margin Top\s+?=\s+?)(1)" 后,我能够使用 " 将值替换为 0 $10”或“$1 0”。
不幸的是,当我运行我的命令时它不起作用:
perl.exe -i.bak -pe "s/(\[Pagebar Button Skin\].+?Margin Top\s+?=\s+?)(1)/$1 0/g" test.txt
这是我的 test.txt 文件中的“[Pagebar Button Skin]”部分:
[Pagebar Button Skin]
Type = BoxStretch
Tile Center = pagebar/top/inactive.png
StretchBorder = 12
Margin Top = 1
Margin Right = -5
Margin Left = -5
Margin Bottom = 0
Padding Left = 12
Padding Top = 5
Padding Right = 9
Padding Bottom = 6
Spacing = 3
Text Color = #111111
编辑:
我必须创建一个 Perl 脚本才能使正则表达式工作。也许 Perl 不喜欢我的 Windows 环境。
命令:
perl.exe skin.pl skin.ini
皮肤.pl:
$/ = undef; # Setting $/ to undef causes <FILE> to read the whole file into a single string.
# Store filename from argument
my $filename = shift;
# Open the file as read only and then store the file text into a string.
open(FILE, "<", $filename) || die "Could not open $filename\n";
my $text = <FILE>;
close(FILE);
# Re-open the file as writable and then overwrite it with the replaced text.
open(FILE, "+>", $filename) || die "Could not open $filename\n";
$text =~ s/(\[Pagebar\s+?Button\s+?Skin\].+?Margin\s+?Top\s+?=\s+?)(1)/${1}0/sg;
#print $text; # Print the text to screen
print {FILE} $text; # Print the text to the file
close(FILE);
【问题讨论】: