Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove lines containing certain substring in Golang

How to remove lines that started with certain substring in []byte, in Ruby usually I do something like this:

lines = lines.split("\n").reject{|r| r.include? 'substring'}.join("\n")

How to do this on Go?

like image 755
Kokizzu Avatar asked Oct 16 '25 16:10

Kokizzu


3 Answers

You could emulate that with regexp:

re := regexp.MustCompile("(?m)[\r\n]+^.*substring.*$")
res := re.ReplaceAllString(s, "")

(The OP Kokizzu went with "(?m)^.*" +substr+ ".*$[\r\n]+")

See this example

func main() {
    s := `aaaaa
bbbb
cc substring ddd
eeee
ffff`
    re := regexp.MustCompile("(?m)[\r\n]+^.*substring.*$")
    res := re.ReplaceAllString(s, "")
    fmt.Println(res)
}

output:

aaaaa
bbbb
eeee
ffff

Note the use of regexp flag (?m):

multi-line mode: ^ and $ match begin/end line in addition to begin/end text (default false)

like image 139
VonC Avatar answered Oct 18 '25 12:10

VonC


I believe using the bytes package for this task is better than using regexp.

package main

import (
    "fmt"
    "bytes"
)

func main() {
    myString := []byte("aaaa\nsubstring\nbbbb")
    lines := bytes.Replace(myString, []byte("substring\n"), []byte(""), 1)

    fmt.Println(string(lines)) // Convert the bytes to string for printing
}

Output:

aaaa
bbbb

Try it here.

like image 30
Stian OK Avatar answered Oct 18 '25 11:10

Stian OK


I believe using the bytes package for this task is better than using regexp.

package main

import (
    "fmt"
    "bytes"
)

func main() {
    myString := []byte("aaaa\nsubstring\nbbbb")
    lines := bytes.Replace(myString, []byte("substring\n"), []byte(""), 1)

    fmt.Println(string(lines)) // Convert the bytes to string for printing
}

Output:

aaaa
bbbb

Try it here.

like image 28
Stian OK Avatar answered Oct 18 '25 11:10

Stian OK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!