首页 > 解决方案 > Sed 搜索条件 - 一个正数和一个负数,但用于精确字符串

问题描述

文件中有一段文字:

1. # OPTIONS="blah --group http blah-blah-blah"
2. OPTIONS="--group http blah-blah-blah --group1 admins"
3. OPTIONS="--group http blah-blah-blah --group1 users2"
4. OPTIONS="--group http blah-blah-blah --group1 user"
5. OPTIONS=" blah-blah-blah --group bind"
6. OPTIONS="blah-blah-blah --group radius --group1 users"
7. OPTIONS "blah-blah-blah --group http --group1 users"
8. OPTIONS="blah-blah-blah --group1 users --group http"

我需要替换--groupfrom httptoradius但仅在行中,满足条件:

  1. OPTIONS=** 行必须以(尤其是非注释行)开头,
  2. *--group1不是在哪里users*
  3. 当然如果*--grouphttp*

即,有2个搜索条件和1个替换条件。

我使用 sed 执行以下操作:

sed -i -r "/(^OPTIONS=.)(.*--group1 [^users].*)/ s/--group http/--group $radius/g" file

在这种情况下,第二个条件是否定的:要么uor要么sor eor ror s , but I need to get negative for the whole exact string users`。

从下面的示例中,只有第 2、3、4 行满足条件。怎么会达到这样?

标签: sed

解决方案


sed有它自己的语言和它自己的 simple ifs。不要写一个表达式。实际写下条件:

sed '
# the line must begginning from OPTIONS= (in particular it is non commented line),
/^OPTIONS=/{
    # where --group1 is NOT users,
    /--group1 users/!{
        # of course if --group is http.
        /--group http/{
            s//--group radius/
        }
    }
}'

推荐阅读