gpt4 book ai didi

regex - 找到匹配项后,Sed 内联替换文本文件中的句子

转载 作者:行者123 更新时间:2023-11-29 09:13:55 24 4
gpt4 key购买 nike

我正在尝试在找到匹配项后替换文本文件中句子的第一个实例。请注意,' 引号包含在搜索中。

  • 我正在搜索以下的第一个实例:'database' => 'localhost'
  • 我将第一个实例替换为:'database' => 'new_database'
  • 我想在字符串'REPLACE_AFTER_THIS'之后替换

我目前有前两个要点:

sed -i file -e "1s/'database' => 'localhost'/'database' => 'new_database'/;t" -e "1,/'database' => 'localhost'/s//'database' => 'new_database'/" file

输入文件

'local config' ... 'data'
'more data'
'database' => 'localhost'
'even more data'
'REPLACE_AFTER_THIS' ... 'data'
'more data'
'even more data'
'database' => 'localhost'
'live config'
'database' => 'localhost'

预期输出文件 (同一文件内联更改)

'local config' ... 'data'
'more data'
'database' => 'localhost'
'even more data'
'REPLACE_AFTER_THIS' ... 'data'
'more data'
'even more data'
'database' => 'new_database'
'live config'
'database' => 'localhost'

上面的例子演示了字符串 'database' => 'localhost' 没有预期的数据格式except,第一次出现需要在之后更改'REPLACE_AFTER_THIS'

但是,我不知道如何 找到特定字符串后才执行上述操作。我曾尝试使用 grep 和模式来检索 REPLACE_AFTER_THIS 之后的所有文本,但随后通过管道传输到 sed 而不是使用 -i 标志不会对文件执行任何更改没有了。

在文件中找到给定字符串后,如何更改当前工作的解决方案以合并替换句子的第一个实例?

最佳答案

用 GNU sed 试试这个:

sed -i "/'REPLACE_AFTER_THIS'/,/'database' => 'localhost'/s/'database' => 'localhost'/'database' => 'new_database'/" file

关于regex - 找到匹配项后,Sed 内联替换文本文件中的句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32069268/

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