查找并替换文件中的配置行

时间:2011-08-15 01:45:47

标签: perl bash sed awk replace

我正在尝试编写一个bash脚本,以便在配置文件中进行一些替换。

conf测试文件是这样的:

pm.max_children = 50
bla bla bla pm.max_children
pm.start_servers = 10
pm.min_spare_servers = 10
pm.max_spare_servers = 30
;pm.max_requests = 20000

我需要做的替换是:

pm.max_children = 5
pm.start_servers = 1
pm.min_spare_servers = 1
pm.max_spare_servers = 3
pm.max_requests = 2000

我需要从bash脚本运行这个程序。

2 个答案:

答案 0 :(得分:3)

这是一个使用sed的简单版本:

#!/usr/bin/sed -f
s/^\(pm.max_children = \).*/\15/
s/^\(pm.start_servers = \).*/\11/
s/^\(pm.min_spare_servers = \).*/\11/
s/^\(pm.max_spare_servers = \).*/\13/
s/^\(pm.max_requests = \).*/\12000/

你能把它放在一个单独的文件中并从你的脚本中调用吗?

我同意Kerrek SB的意见 - 如果你解释一下你想要完成的事情会有所帮助!

答案 1 :(得分:2)

#!/usr/bin/perl
use warnings;
use strict;

my %vals = (
    'pm.max_children'      => 5,
    'pm.start_servers'     => 1,
    'pm.min_spare_servers' => 1,
    'pm.max_spare_servers' => 3,
    'pm.max_requests'      => 2000,
);

while (<DATA>) {
    if ( my($param) = /^(\S+)\s*=/ and exists $vals{$1} ) {
        s/\d+$/$vals{$param}/;
    }
    print;
}

__DATA__
pm.max_children= 50
bla bla bla pm.max_children
pm.start_servers = 10
pm.min_spare_servers = 10
pm.max_spare_servers = 30
pm.max_requests = 20000