分页: 1 / 1

请教如何使用sed命令实现这样的功能

发表于 : 2010-12-07 21:20
wolfboy
现在有一张配置表,形如:
[group1]
key1 = value1
key2 = value2
……
[group2]
key1 = value1
key2 = value2
……
[group3]
key1 = value1
key2 = value2

现在希望通过sed命令对其进行操作
第一个问题是:如果删除一个组,就将指定的group连同key值一并删除
由于组与组之间没有空格等分隔标识,因此我这样想的
以删除group1为例例子
需要锚定[group1]到其下第一个‘[’所有的行,但是不包括最后一行,因为这样锚定的话,最后一行就是下一组的组名了。
但是怎么才能实现对 sed -n -e "/\[group1\]/,/\]/" 但是不包括最后一行实现删除操作n呢?

第二个问题是:如果要在某个组中追加key值,如何才能实现在组的末尾实现追加。

Re: 请教如何使用sed命令实现这样的功能

发表于 : 2010-12-07 22:34
millenniumdark
別想只用sed,sed不是萬能的,寫腳本囉。比如,用grep搞出行數,減一,再讓sed來。

Re: 请教如何使用sed命令实现这样的功能

发表于 : 2010-12-08 10:27
eexpress
sed可批量,只是太晦涩。
脚本搞一个循环吧。

Re: 请教如何使用sed命令实现这样的功能

发表于 : 2010-12-08 16:00
tusooa

代码: 全选

#!/usr/bin/env perl

use 5.010;

$file = 'test';
open (FILE, '<', $file) || die "Cannot open $file: $!\n";
@_ = <FILE>;
close FILE;

# Delete
$groupToDelete = $ARGV[0];
for (0..$#_)
{
    if ($_[$_] =~ /^\[$groupToDelete\]$/)
    {
        $_[$_] = '';$next = 1;next;
    }
    if ($next)
    {
        unless ($_[$_] =~ /^\[/)
        { $_[$_] = '';} else { $next = 0; next; }
    }
}

open (FILE, '>', $file);
for (@_){print FILE unless /^$/;}
close FILE;


Re: 请教如何使用sed命令实现这样的功能

发表于 : 2010-12-10 0:04
wolfboy
tusooa 写了:

代码: 全选

#!/usr/bin/env perl

use 5.010;

$file = 'test';
open (FILE, '<', $file) || die "Cannot open $file: $!\n";
@_ = <FILE>;
close FILE;

# Delete
$groupToDelete = $ARGV[0];
for (0..$#_)
{
    if ($_[$_] =~ /^\[$groupToDelete\]$/)
    {
        $_[$_] = '';$next = 1;next;
    }
    if ($next)
    {
        unless ($_[$_] =~ /^\[/)
        { $_[$_] = '';} else { $next = 0; next; }
    }
}

open (FILE, '>', $file);
for (@_){print FILE unless /^$/;}
close FILE;


收到 正在研究~感谢~

Re: 请教如何使用sed命令实现这样的功能

发表于 : 2010-12-10 0:05
wolfboy
eexpress 写了:sed可批量,只是太晦涩。
脚本搞一个循环吧。
是的,我刚想了个办法,用循环实现的。写了个函数来锚定group的范围。
通过判断最后一行是不是下一组开始来确定组结尾的行数。