gpt4 book ai didi

bash - 仅对文件的特定部分执行搜索和替换的最佳方法是什么?

转载 作者:行者123 更新时间:2023-12-02 16:14:58 25 4
gpt4 key购买 nike

我有一个 markdown 文件,其中的部分由标题分隔。我只想在特定部分执行搜索和替换;但是,每个部分都有相似的内容,因此全局搜索和替换最终会影响所有部分。因此,我需要以某种方式将搜索和替换限制为文件的某些部分。

例如,假设我想用 # Section 1 下的 bar 替换 fooall 个实例, #Section 3#Section 4保留#Section 2#Section 5不变,如下所示

示例输入:

# Section 1

- foo
- foo
- Unimportant Item
- foo
- Unimportant Item

# Section 2

- foo
- Unimportant Item

# Section 3

- foo
- Unimportant Item

# Section 4

- foo
- Unimportant Item
- foo

# Section 5

- foo
- foo

示例输出

# Section 1

- bar
- bar
- Unimportant Item
- bar
- Unimportant Item

# Section 2

- foo
- Unimportant Item

# Section 3

- bar
- Unimportant Item

# Section 4

- bar
- Unimportant Item
- bar

# Section 5

- foo
- foo

如果我不必担心各个部分,则使用全局搜索和替换将是微不足道的

sed -i 's/foo/bar/g' <input_file>

但我不确定 sed 是否能够检查上下文以允许我正在寻找的内容。

最佳答案

这是一个 sed 版本:

sed -E '/^#[^#]\s*Section\s+[134]\s*$/, // s/foo/bar/' input.md

关于bash - 仅对文件的特定部分执行搜索和替换的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66960184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com