regex - 查找特定标签并在 perl 中替换其下的所有字段

标签 regex linux perl find

我有一个如下内容的文件

[amrit]
type=friend
host=111.118.253.145
port=2776
username=amrit
secret=password
disallow=all
allow=gsm
context=sip-calling
qualify=yes
call-limit=22

[windwos]
type=friend
host=111.118.253.145
port=2775
username=amrit
secret=password
disallow=all
allow=gsm
context=sip-calling
qualify=yes
call-limit=50


[windwos121254]
type=friend
host=111.118.253.145
port=2776
username=amrit
secret=password
disallow=all
allow=ulaw
allow=alaw
context=sip-calling
qualify=yes
call-limit=99

现在我想在 perl 中创建一个脚本。这将找到 [amrit] 这个标签下的所有行

type=friend
host=111.118.253.145
port=2776
username=amrit
secret=password
disallow=all
allow=gsm
context=sip-calling
qualify=yes
call-limit=22

现在我想更新每个字段的值,但值应该是这个标签的更改,只有我使用 perl 脚本找到这些行,但我无法更改这些字段的值。脚本如下

#!/usr/bin/perl
$count = 0;
open (IN, "file.txt");
while (<IN>) {
    if (/\[amrit\]/) {
    $count = 1;
    }
    elsif (/\[*\]/) {
    $count = 0;
    }
    elsif ($count) {
    print;
      }
}
close IN;

现在我想更新 [amrit] 标签中每一行的值。我是 perl 的初学者,请在这里帮助我。

最佳答案

Config::Tiny在这里满足您的需求。

#! /usr/bin/perl -w

    use strict;
    use Config::Tiny;

    my $config = Config::Tiny->read('test.ini');

    my $section ="amrit";

    print "[$section]\n";
    foreach my $parameter (keys %{$config->{$section}}) 
    {
        print "\t$parameter = $config->{$section}->{$parameter}\n"; 
    }

这里是读取特定标签数据的脚本。

你可以通过这个设置值

 $Config->{section}->{username} = 'No user';     # Change a value

还有如下更有用的api

  # Changing data
    $Config->{newsection} = { this => 'that' }; # Add a section
    $Config->{section}->{Foo} = 'Not Bar!';     # Change a value
    delete $Config->{_};                        # Delete a value or section

关于regex - 查找特定标签并在 perl 中替换其下的所有字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21747000/

相关文章:

php - 修改脚本中的正则表达式,通过向它们添加跨度类来突出显示文本中的某些单词

python - Multiprocessing.Pool中如何区分进程?

linux - Yocto 项目中是否有任何 'Project File' 或 'Workspace file' 或 'Solution file' 等价物?

Perl/CPAN 如何分发脚本而不是模块

regex - 为什么这两个RegEx基准测试有如此大的差异?

perl - 禁止 Moose 类中的非属性参数

regex - git存储库的正则表达式

regex - 相同连续数字的正则表达式

javascript - 在 JavaScript 中使用正则表达式

php - 从 apache 服务器中的 php 访问 shell 可执行文件