首页 > 解决方案 > 正则表达式搜索文件中的部分或文本块中的内容

问题描述

我有一个文件,内容如下。我需要分别在每个内容部分下搜索端口号。

路径:etc/a.Config 文件

 Global
  user abc
  group aaa

 frontend one
  bind 10.1.0.15:80
  option tcp

 frontend two
  bind 10.1.1.25:666
  option tcp 

 frontend three 
  bind 10.2.2.45:444
  option tcp

输出应该是:

  frontend one port: 80
  frontend two port: 666
  frontend three port: 444

什么是完整的正则表达式,因为我需要在同一文件的每个文本部分下搜索端口号。搜索是针对配置文件中的内容模式完成的,但是我根据 puppet 的需要在 ruby​​ 文件中编写代码,如果它在 ruby​​ 中,它对正则表达式有什么影响吗?

标签: regexlinuxdevops

解决方案


这是一个进行匹配的正则表达式......如何将其应用于我留给你的整个文件;)

$ cat a
#!/usr/bin/ruby

text = " Global
  user abc
  group aaa

 frontend one
  bind 10.1.0.15:80
  option tcp
"
m = text.match /(frontend [^ ]+)\n.*bind [^:]+:([0-9]+)/
puts "#{m[1]} port: #{m[2]}"

$ ./a
frontend one port: 80

解释词:

/  # the slashes start and terminate the regex
(  # start a capturing group, capturing subexpressions matching the following line
frontend [^ ]+  # a literal frontend followed by a space followed by at least one non-space
)  # close capturing group
\n.*  # match new line, followed by any number of any character  
bind [^:]+:  #  match the word bind followed by a space followed by at least one non-colon followed by a colon
(
[0-9]+  # captured digits, one at the least
)
/
# m is an array that holds captured results from above.

推荐阅读