如何使用Perl来增加CSS属性值

时间:2013-12-17 19:26:14

标签: css regex perl

我支持由外部公司编写的网站,所以虽然有更好的方法可以维护CSS样式定义,但我在多个CSS文件中有以下定义要修复:

.rect_frame {
   width: 980px;
   height: 2882px;
   padding: 0px;
   overflow: hidden;
}

.rect_headline1 {
   font-family: Arial;
   font-size: 20px;
   font-weight: bold;
}

“。rect_frame”类具有高度设置,但会根据页面而有所不同。我需要在每个页面上为该类添加65像素高度来修复页脚。为此,我尝试了一些Perl正则表达式,以下脚本失败:

#! /usr/bin/perl

use warnings;
use strict;

-pi -e 's/(\.rect_frame\s{[.\r\s\w:;]*.height:\s)(\d*)/$1.$2+65/e' ./*.css;

我已经检查了正则表达式,所以我认为这并不完全是Perl需要的。在将其作为Perl脚本运行时,您能帮助找到我需要的语法吗?

打破正则表达式:

(                -> start first set to grab
\.rect_frame\s{  -> grabs the initial class
[.\r\s\w:;]*     -> grab the rest of material from thereon
*.height:\s      -> stops grabbing after the height property and a space
)                -> end the first set to grab, used as $1
(\d*)            -> the digits to grab and add 65 to using the "/e" modifier, used as $2

从而取代:

$1.$2+65

结果:

Search pattern not terminated at ./fix_height_style.pl line 6.

这是专门解决Perl问题的。其他语言和模块我欢迎,但我确实想在Perl中为自己的学习解决这个问题。如果这是一个简单的语法错误,我很抱歉。

2 个答案:

答案 0 :(得分:1)

#!/usr/bin/perl

# Usage:
#    script <in.css >out.css        Read from a STDIN
#    script in.css >out.css         Read from a file
#    perl -i script file(s).css     In-place without backup
#    perl -i~ script file(s).css    In-place with backup

use warnings;
use strict;

local $/;

while (<>) {
   s/.../.../eg;
}

local $/;使<>读取整个文件,而不是一次只读一行。

答案 1 :(得分:1)

这是我使用的解决方案。我承认更好的字符串替换解决方案,节省内存,来自更有经验的Perl程序员的文件处理:

use strict;
use warnings;

my $input;  # hold the lines to split
my $regex = '(\.rect_frame\s+\{[^}]*?\sheight:\s+)(\d+)';  # regular expression
my @css_array; # array of split lines

my @files = <*.css>; # get list of all CSS files in directory
foreach my $filename (@files) {
    open(INPUT_FILE, "$filename")
        or die "Cannot open file: $!.";
    while (<INPUT_FILE>) {
        $input = $input.$_;  # grab the lines
    }
    close(INPUT_FILE); # already have the lines, so close the file
    open(OUTPUT_FILE, ">$filename") # replace original CSS by opening as append
        or die "Cannot write to file: $!.";
    @css_array = split($regex,$input);  # split lines with regular expression
    print OUTPUT_FILE $css_array[1].($css_array[2]+65).$css_array[3];  # overwrite the file
    close(OUTPUT_FILE);
    $input = ''; # get ready for the next file's lines
}

感谢@mob,@ kjpires和其他评论。进一步的帮助: www.regexplanet.com/advanced/perl/index.html,alumnus.caltech.edu/~svhwan/prodScript/perlGettingInput.html,clipoverflow.com/a/2149386/3112527,www.perl.com。