gpt4 book ai didi

awk - 使用 sed 和 regex 替换配置文件的部分

转载 作者:行者123 更新时间:2023-12-02 01:39:27 24 4
gpt4 key购买 nike

我的配置文件结构如下:

[section1]
path = <path1>
read only = yes
guest ok = yes

[section2]
path = <path2>
read only = no
guest ok = yes

我需要能够使用 sed 命令将配置文件的整个部分替换为新部分。我想要实现的示例:

sudo sed -E -i ':a;N;$!ba;\[section1\]<regex_match_until_end_of_section1>/<new_section_1>/' <config_path>

预期结果:

<new_section_1>

[section2]
path = <path2>
read only = no
guest ok = yes
sudo sed -E -i ':a;N;$!ba;\[section2\]<regex_match_until_end_of_section2>/<new_section_2>/' <config_path>

预期结果:

[section1]
path = <path1>
read only = yes
guest ok = yes

<new_section_2>

最佳答案

虽然 sed 可能能够做到这一点,但使用 awk 更加直观和干净:

awk -v s='[section1]' -v RS= '$1 == s {$0 = "<new_section_1>"}
{ORS=RT} 1' file

<new_section_1>

[section2]
path = <path2>
read only = no
guest ok = yes

或者:

awk -v s='[section2]' -v RS= '$1 == s {$0 = "<new_section_2>"} 
{ORS=RT} 1' file

[section1]
path = <path1>
read only = yes
guest ok = yes

<new_section_2>

关于awk - 使用 sed 和 regex 替换配置文件的部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71855078/

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