【问题标题】:Combine Grep and Regex?结合 Grep 和正则表达式?
【发布时间】:2015-05-21 13:42:09
【问题描述】:

有一个我试图在标准输出中列出的较小网络元素的列表。 我的小脚本一直运行到正则表达式,在我收到提示后我要搜索它列出整行。

例子:

请输入地区

输入:北

输出

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

【问题讨论】:

    标签: ruby regex input while-loop stdout


    【解决方案1】:

    您可以尝试像这样循环遍历 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 会让事情更清晰)

    【讨论】:

    • 像魅力一样工作,正是我想要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多