用 sed 匹配另一行上的模式后替换后面的行

问题描述 投票:0回答:1

我正在尝试使用 sed 来查找并替换我拥有的大文件 python 文件。

该文件包含字典列表中的许多项目。每个字典都包含一个

name
字段。我想找到特定的名称,然后更改字典中的其他字段之一。

示例文件,为简洁起见进行了简化:

Books = [
    Book(
        name="foo-job",
        other_field=z
        min_tasks=Var(default=1, prod=4)
        max_tasks=Var(default=4, dev=238)
    ),
    Book(
        name="foo-task",
        other_field=a
        min_tasks=Var(default=1, prod=14)
        max_tasks=Var(default=4, prod=82)
    ),
    Book(
        name="bar-job",
        other_field=x
        other_field1=y
        other_field2=y
        other_field3=y
        min_tasks=Var(default=1, dev=4)
        max_tasks=Var(default=4, dev=8)
    ),
    Book(
        name="bar-task",
        other_field=y
        other_field=f
        min_tasks=Var(default=1, prod=42)
        max_tasks=Var(default=4, prod=83)
    ),
]

扔在那里的

other_field
字段只是为了证明
name=
min_tasks
线之间存在数量未知且不规则的线。

假设我想找到 bar-task,然后将 bar-task 条目中的

min_tasks
值替换为
0

我想出的 sed 命令是:

sed -iE "/name=\"bar-task"/{:a;N;s/\s*min_tasks=(.*)/\1=0/};" books.py

这运行时没有错误,但不会改变任何东西。

如有任何指点,我们将不胜感激。

sed
1个回答
0
投票

试试这个:

sed -i '/name="bar-task"/,/min_tasks/s/min_tasks=Var(default=[0-9]+, prod=[0-9]+)/min_tasks=Var(default=0, prod=0)/' books.py

说明:

/name="bar-task"/: Matches the line containing the specified name.
{:a;N;/min_tasks/: Marks a label a, appends the next line to the pattern space, and checks if it contains min_tasks.
s/min_tasks=Var(default=[0-9]*, prod=[0-9]*)/min_tasks=Var(default=0, prod=0)/: If the line contains min_tasks, it replaces the min_tasks value with 0.

此命令将搜索 name="bar-task" 的行,然后找到包含 min_tasks 的行,并将其值替换为 0。

© www.soinside.com 2019 - 2024. All rights reserved.