匹配一个子串并在同一行替换另一个

Match one substring and replace another on same line

我想将包含 should-log 子字符串的所有行的所有 true 值更改为 false,输入文件包含其他行但未在此代码段中提及:

logging.ap.should-log-headers = true
logging.ap.should-log-password = true
logging.api.should-log-headers = true
logging.httpbin.should-log-headers = true
logging.httpbin.should-log-password = true
logging.copy.should-log-headers = false
logging.copy.should-log-password = false
logging.test.should-log-headers = false
logging.test.should-log-password = false
logging.-test.should-log-password = true
logging.hu.should-log-headers = true
logging.madf.should-log-headers = true
logging.madf.should-log-password = true
logging.api-f-002.should-log-headers = true
logging.f.should-log-headers = true
logging.f-d.should-log-headers = true
logging.f-d.should-log-password = true
logging.copy-d.should-log-headers = false
logging.copy-d.should-log-password = false
logging.d.should-log-headers = false
logging.d.should-log-password = false
logging.e.should-log-headers = true
logging.e.should-log-password = true

我在尝试什么:

sed -i -E '/should-log=/{s/true/false/;}' infile

但是它不起作用,我做错了什么,我该怎么办?

should-log= 不匹配任何给定的输入行。您可以使用 should-log-should-log.*=should-log-.*=.

此外,地址后的单个命令不需要 {} 分组。

正则表达式引擎从左到右搜索匹配项。当您写 should-log= 时,搜索从字符串的开头开始,搜索 s。一旦找到 s,正则表达式引擎检查下一个字符,如果它是 h,它继续检查,一旦找到 g 后到达 =,有失败,在 g.

之后没有 =

您需要确保您允许正则表达式引擎实际到达 (=consume) 您想要的字符串部分.

因为在 g 之后你需要到达第一个 =,匹配除 = 之外的任何零个或多个字符是合乎逻辑的,所以你可以使用

sed -i -E 's/(should-log[^=]*= *).*/false/' file

online demo。 POSIX ERE(参见 -E)正则表达式匹配

  • ( - ID 为 1 的捕获组的开始(其值在替换模式中用 </code> 引用): <ul> <li><code>should-log - should-log
  • [^=]* - 匹配除 =
  • 之外的零个或多个字符的否定括号表达式
  • = - 一个 = 字符
  • *
  • ) - 捕获组结束
  • .* - 该行的其余部分。
  • 请注意 sed -i -E '/should-log[^=]*=/s/true/false/' file 不太精确,因为 might replace true 不在 should-log[^=]*=.

    之后