hylian
hylian

Reputation: 560

Splitting strings in 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, "\n")
    fmt.Printf("start split: \n", split)
}

Any tips?

thanks

Upvotes: 1

Views: 5883

Answers (1)

adamyi
adamyi

Reputation: 547

Try this.

func splitOutput(outs []byte) {
    outputStr := string(outs[:])
    split := strings.Split(outputStr, "\n")
    fmt.Printf("Splitted result: %q\n", split)
    for index, line := range split {
        fmt.Printf("Line %d: %s\n", 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\n", name, lineSplit[6], lineSplit[12])
            }
        }
    }
}

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

Upvotes: 3

Related Questions