如何使用单行更新INI文件中的名称?

时间:2011-04-13 08:52:01

标签: regex perl replace ini

使用Perl one-liner regex命令替换INI文件的特定部分中的值?

我想将“Margin Top”值1替换为0.该部分必须为“[Pagebar Button Skin]”。

我尝试了“(\ [Pagebar Button Skin \]。+?Margin Top \ s +?= \ s +?)(1)”在RegExr中使用global和dotall,我能够用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

skin.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);

4 个答案:

答案 0 :(得分:4)

使用Config::Tiny之类的专用模块来解析配置文件。单线使用它:

perl -MConfig::Tiny -we '$file = shift; $config = Config::Tiny->read($file); $config->{"Pagebar Button Skin"}->{"Margin Top"} = 0; $config->write($file)' test.txt

答案 1 :(得分:3)

不要用正则表达式来做。使用模块。 CPAN有Config::INIConfig::IniFiles

答案 2 :(得分:2)

由于ini文件通常处于段落模式,您可以尝试:

perl -p00 -e '/Pagebar Button Skin/ && s/(Margin Top.*=)\s*\d/$1 0/' file.ini

输出:

[Pagebar Button Skin]
Type                        = BoxStretch
Tile Center                 = pagebar/top/inactive.png
StretchBorder               = 12
Margin Top                  = 0
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

如果您对结果感到满意,请将-i.bak添加到单行

答案 3 :(得分:1)

尝试一下

perl -pe 'if (/^\s*\[Pagebar Button Skin\]/../^\s*\[/) { s/(Margin\s+Top\s*=\s*)1/${1}0/ }'

这将仅在Pagebar部分的开头和下一部分之间应用替换。此外,您可以使用一些INI模块,将文件作为结构读入perl,更改您想要的内容并将其写出来。取决于哪种更适合您的需求。