How can a name in an INI file be updated using a one-liner?
Replace value in a specific section of an INI file using Perl one-liner regex command?
I want to replace the "Margin Top" value of 1 to 0. The section must be "[Pagebar Button Skin]".
After I tried "(\[Pagebar Button Skin\].+?Margin Top\s+?=\s+?)(1)" with global and dotall in RegExr, I was able to replace the value with 0 using "$10" or "$1 0".
Unfortunately, it doesn't work when I run my command:
perl.exe -i.bak -pe "s/(\[Pagebar Button Skin\].+?Margin Top\s+?=\s+?)(1)/$1 0/g" test.txt
Here is the "[Pagebar Button Skin]" section in my test.txt file:
[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
EDIT:
I had to create a Perl script in order to get the regex to work. Maybe Perl doesn't like my Windows environment.
Command:
perl.ex开发者_StackOverflowe 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);
Use a specialised module like Config::Tiny
for parsing configuration files. A one-liner using it:
perl -MConfig::Tiny -we '$file = shift; $config = Config::Tiny->read($file); $config->{"Pagebar Button Skin"}->{"Margin Top"} = 0; $config->write($file)' test.txt
Don't do it with a regex. Use a module. CPAN has Config::INI and Config::IniFiles.
Since ini files are usually in paragraph mode you can try:
perl -p00 -e '/Pagebar Button Skin/ && s/(Margin Top.*=)\s*\d/$1 0/' file.ini
Output:
[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
Once you are satisfied with the results add -i.bak to one-liner
Try something along the line
perl -pe 'if (/^\s*\[Pagebar Button Skin\]/../^\s*\[/) { s/(Margin\s+Top\s*=\s*)1/${1}0/ }'
This will apply the substitution only between the start of the Pagebar section, and the next section. Also, you can use some INI module, read the file into perl as structure, change what you want and write it out. Depends on what better suits your needs.
精彩评论