regexp和sed在多行块中查找字符串的块,直到它以空格结束

nhaq1z21  于 12个月前  发布在  其他
关注(0)|答案(3)|浏览(153)

我尝试捕获这些字符串块,并使用regexp和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

字符串
我尝试使用这个regexp:

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}

vuv7lop3

vuv7lop31#

使用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

insrf1ej

insrf1ej2#

一个更简单的sed解决方案可能是这样的,如果你同意最后一个空行也被注解的话:

sed '/^AppServer1:/,/^[[:space:]]*$/s/^/# /' lines.txt

个字符
它使用sed范围模式,用逗号表示(,)。范围的开始是/^AppServer1:/,即,从(^)和AppServer1:。范围的结尾是一个空行或只包含空白字符的行:/^[[:space:]]*$/,其中^:行的开头; [[:space:]]*:零个或多个(*)空白字符([[:space:]]); $:行尾。
接下来是[s] substitution命令-s/^/# /-它将匹配范围内所有行(包括end)的行^的开始替换为序列#
如果你想要一个不区分大小写的匹配,你需要GNU sed。在这种情况下,你可以将I标志添加到范围开始模式。但是这个标志在macOS sed上不可用。

biswetbf

biswetbf3#

假设输入中看起来为空的行实际上是空的,你可以在每个Unix机器上的任何shell中使用任何awk来做到这一点:

$ awk -v RS= -v ORS='\n\n' '/^AppServer1:/{gsub(/^|\n/,"&#")} 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

字符串

相关问题