Search code examples
gostring-parsing

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?


Solution

  • 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)