Start learning free

LESSON 377 OF 404 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: grep v3 — Invert Match in Go

Practice

Build the -v flag of the Unix grep command. Given a list of lines and a search pattern, return all lines that DO NOT contain pattern as a substring (case-sensitive). Return the remaining lines (the ones that do not contain the pattern), in their original order, joined by newline characters (\n).

Function signature:

func grepInvert(lines []string, pattern string) string

Example:

Input:
pattern = "err"
lines = ["error", "ok", "another error", "fine"]

Output: "ok\nfine"

When printed:
ok
fine

If every line contains the pattern, return the empty string "".


Same as grep v1 but flip the condition: keep the lines where !strings.Contains(line, pattern) is true, then return strings.Join(result, "\n").

The full solution:
func grepInvert(lines []string, pattern string) string {
    result := []string{}
    for _, line := range lines {
        if !strings.Contains(line, pattern) {
            result = append(result, line)
        }
    }
    return strings.Join(result, "\n")
}

STEP 1 OF 5
    Ctrl + Enter to check

    Grep V3 in Go

    Keep going with GoAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free