正则表达式和 sed 在多行 block 中查找字符串 block ,直到它以空格结尾

标签 regex string sed comments multilinestring

我 try catch 这些字符串块并使用正则表达式和 sed 对它们进行注释。
每个块用空格分隔

some text here 
some text here 

AppServer1:
  name: ${AppServer1.name}
  ip: ${AppServer1.ip}
   
some text here 
some text here 

AppServer2:
  name: ${AppServer1.name}
  ip: ${AppServer1.ip}

some text here 
some text here 
   
我尝试使用这个正则表达式:
sed E '/./{H;1h;$!d} ; x ; s/[^\$AppServer1](AppServer1)/#\1/gi'
但结果是:
 #AppServer1:
      name: $#{AppServer1.name}
      ip: $#{AppServer1.ip}
我在这里缺少评论完整字符串的内容:
#AppServer1:
#      name: ${AppServer1.name}
#      ip: ${AppServer1.ip}

最佳答案

使用 gnu-sed , 你可以这样做:

sed '/^AppServer1/I{:a; /^[[:blank:]]*$/!{s/.*/#&/; n; ba;} }' file

some text here
some text here

#AppServer1:
#  name: ${AppServer1.name}
#  ip: ${AppServer1.ip}

some text here
some text here

AppServer2:
  name: ${AppServer1.name}
  ip: ${AppServer1.ip}

some text here
some text here
详情:
  • /^AppServer1/I : 搜索 AppServer1不区分大小写
  • { : 块启动
  • :a : 制作标签a
  • /^[[:blank:]]*$/!如果一行不是空行
  • {s/.*/#&/; n; ba;} :在每一行前面加上 # , 阅读下一行并转到标签 a

  • } : 座结束

  • 使用 awk你可以这样做:
    awk '/^AppServer1/ {b=1} b && !NF {b=0} b {$0 = "#" $0} 1' file
    
    some text here
    some text here
    
    #AppServer1:
    #  name: ${AppServer1.name}
    #  ip: ${AppServer1.ip}
    
    some text here
    some text here
    
    AppServer2:
      name: ${AppServer1.name}
      ip: ${AppServer1.ip}
    
    some text here
    some text here
    

    关于正则表达式和 sed 在多行 block 中查找字符串 block ,直到它以空格结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68725975/

    相关文章:

    linux - 获取 KSH 名称

    python - 了解正则表达式

    perl - 将 Unix `cal` 输出转换为 Latex 表代码 : one-liner solution?

    php - 用其他数组中的值替换数组中的占位符

    java - 无法在 Switch 语句中实例化字符串数组 - Java

    regex - 句子中的最后一个单词 : In SQL (regular expressions possible? )

    比较文本文件中的字符串,然后打印整行

    linux - 如何在文件中的特定字符串附近附加一个字符串?

    python - 如何在 Python 中仅替换一次正则表达式?

    javascript - 验证文本字段中的数值未给出所需结果