douan5151
douan5151
2017-08-17 02:40
浏览 30
已采纳

在Golang中分割字串

I am learning Go and am attempting to build a tool to monitor license usage.

I'm able to run the command OK and store the output to file fine, what I'd like to do now is split key data out of the below output.

As an example, I run the command and it will return this example output.

lmutil - Copyright (c) 1989-2015 Flexera Software LLC. All Rights Re
served.
Flexible License Manager status on Thu 8/17/2017 12:18

[Detecting lmgrd processes...]
License server status: 28000@servername
License file(s) on servername: C:\Program Files\autocad\LM\autocad.lic:

servername: license server UP (MASTER) v11.13.1

Vendor daemon status (on servername):

autocad: UP v11.13.1
Feature usage info:

Users of autocad:  (Total of 1 license issued;  Total of 0 licenses in use)

Users of feature2:  (Total of 1000 licenses issued;  Total of 0 licenses in us
e)

I'd like to loop through each line and grab the feature name 'Users of %feature%', total of licenses issued and total in use.

I know in python I can use something like

for line in output.splitlines(true):

but this is about as far as I've gotten in Go.

func splitOutput(outs []byte) {
    outputStr := string(outs[:])
    split := strings.Split(outputStr, "
")
    fmt.Printf("start split: 
", split)
}

Any tips?

thanks

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doujujian0052
    doujujian0052 2017-08-17 02:59
    已采纳

    Try this.

    func splitOutput(outs []byte) {
        outputStr := string(outs[:])
        split := strings.Split(outputStr, "
    ")
        fmt.Printf("Splitted result: %q
    ", split)
        for index, line := range split {
            fmt.Printf("Line %d: %s
    ", index, line)
            if len(line) >= 9 && line[0:9] == "Users of " {
                lineSplit := strings.Split(line, " ")
                if len(lineSplit) == 16 {
                    name := lineSplit[2]
                    name = name[0:len(name) - 1]
                    fmt.Printf("%s %s %s
    ", name, lineSplit[6], lineSplit[12])
                }
            }
        }
    }
    

    Test it online: https://play.golang.org/p/m6JIBytU0m

    点赞 评论

相关推荐