结合 Grep 和 Regex?
Combine Grep and Regex?
有一个我试图在标准输出中列出的较小网络元素的列表。
我的小脚本一直运行到正则表达式,在我收到提示我要搜索的内容后,它列出了整行。
示例:
请输入地区
输入:贝
输出:
ipc-bei640-r-br-01
ipc-bei640-r-br-02
ipc-bei640-r-br-03
而不是:
bei640-01
bei640-02
bei640-03
此外,如果我在输入中点击 "Enter",它会列出所有设备。
lines = IO.readlines("/usr/local/bin/braslist.txt")
devices = []
str = File.read('braslist.txt')
while true
print "Please enter a region. If you want to exit enter exit "
input = gets.chomp
exit if input == 'exit'
#Opens file and greps for input
File.open("braslist.txt", "r+") do |f|
f.each do |line|
devices += line.split(" ").grep(/#{input}/i)
input.scan(/^ipc-(?<bng>[a-z]{3}\d{3})-r-br(?<nr>-\d{2})$/).map(&:join)
end
end
puts devices
puts "#{devices.length} network elements found"
end
您可以尝试像这样遍历 grep 的结果:
File.open("braslist.txt", "r+") do |f|
f.each do |line|
line.split(" ").grep(/#{input}/i).each do |string|
match = string.match(/^ipc-(?<bng>[a-z]{3}\d{3})-r-br(?<nr>-\d{2})$/)
devices << match[:bng] + match[:nr]
end
end
end
(我也认为使用 match 而不是 scan 可以使事情更清晰一些)
有一个我试图在标准输出中列出的较小网络元素的列表。 我的小脚本一直运行到正则表达式,在我收到提示我要搜索的内容后,它列出了整行。
示例:
请输入地区
输入:贝
输出:
ipc-bei640-r-br-01
ipc-bei640-r-br-02
ipc-bei640-r-br-03
而不是:
bei640-01
bei640-02
bei640-03
此外,如果我在输入中点击 "Enter",它会列出所有设备。
lines = IO.readlines("/usr/local/bin/braslist.txt")
devices = []
str = File.read('braslist.txt')
while true
print "Please enter a region. If you want to exit enter exit "
input = gets.chomp
exit if input == 'exit'
#Opens file and greps for input
File.open("braslist.txt", "r+") do |f|
f.each do |line|
devices += line.split(" ").grep(/#{input}/i)
input.scan(/^ipc-(?<bng>[a-z]{3}\d{3})-r-br(?<nr>-\d{2})$/).map(&:join)
end
end
puts devices
puts "#{devices.length} network elements found"
end
您可以尝试像这样遍历 grep 的结果:
File.open("braslist.txt", "r+") do |f|
f.each do |line|
line.split(" ").grep(/#{input}/i).each do |string|
match = string.match(/^ipc-(?<bng>[a-z]{3}\d{3})-r-br(?<nr>-\d{2})$/)
devices << match[:bng] + match[:nr]
end
end
end
(我也认为使用 match 而不是 scan 可以使事情更清晰一些)