Start learning free

LESSON 15 OF 69 · PROJECTS: COMMAND-LINE TOOLS

grep -v in Go: Inverting a Match with !strings.Contains

Practice Read the full explanation

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

    GO · PROJECTS: COMMAND-LINE TOOLS

    Grep V3 in Go, explained

    Problem overview

    The function grepInvert(lines []string, pattern string) string is the -v flag of Unix grep: it returns the lines that do not contain pattern, in their original order, joined by newline characters (\n). The match is case-sensitive.

    With pattern = "err" and lines = ["error", "ok", "another error", "fine"], the first and third lines contain err, so they are dropped and the result is "ok\nfine". If every line contains the pattern, nothing is left and the result is "".

    Approach

    This is the first version's filter turned upside down. Version 1 kept a line when strings.Contains(line, pattern) was true. Here a line is kept when that call is false. Everything else, the empty result slice, the loop, the append and the final join, stays the same.

    In Go, putting ! in front of a boolean expression negates it. So the single change to the code is !strings.Contains(line, pattern). That is the whole feature, which makes this a good example of how a small, well-chosen building block can be reused in the opposite direction.

    Step by step

    1. Create the empty result slice for the lines to keep.
    2. Loop over the lines with for _, line := range lines.
    3. Test for absence. if !strings.Contains(line, pattern) is true exactly when the pattern does not appear in the line.
    4. Keep the line. result = append(result, line), storing the grown slice back in result.
    5. Join with newlines and return. Joining an empty slice gives "", which is the required answer when every line contained the pattern.

    The solution in Go

    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")
    }
    

    A few notes on the code:

    • ! is the logical NOT operator. Go has no not keyword. The operator applies to the call that follows it, so !strings.Contains(line, pattern) reads "the line does not contain the pattern".
    • The order is preserved. Lines are appended as the loop meets them, so the output follows the input's order.
    • Tabs for indentation. Go's formatter indents with tabs, which is why this solution uses them. Indentation has no effect on how the code runs.
    • The line is added as it is. Empty lines don't contain a non-empty pattern, so they are kept: ["a", "", "b"] with pattern "x" returns "a\n\nb", with an empty line in the middle.

    Complexity

    Time: O(n * m) in the worst case, where n is the total length of the lines and m the length of the pattern, since each line is searched once. Space: O(k), where k is the size of the output: the kept lines are stored in result and then copied into one joined string.

    Edge cases and common mistakes

    • Every line matches. ["error", "another error"] with "err" gives "".
    • Empty pattern. Every string contains the empty string, so every line is rejected: ["error", "ok"] with "" gives "".
    • Empty list. Nothing is visited and the result is "".
    • Case-sensitive test. ["Error", "ok"] with "err" returns "Error\nok": Error starts with a capital, so it doesn't contain the lowercase err and survives.
    • Forgetting the !. Without it the function behaves like version 1 and returns exactly the lines it should drop.
    • Parentheses. ! binds to the nearest expression. In !strings.Contains(line, pattern) it applies to the call's result, as intended. If the test grows to something like !a && b, it applies to a only, and parentheses are needed to negate the whole condition.

    Testing

    • ["error", "ok", "another error", "fine"] with "err" gives "ok\nfine".
    • ["error", "another error"] with "err" gives "".
    • ["Error", "ok"] with "err" gives "Error\nok".
    • ["a", "", "b"] with "x" gives "a\n\nb".
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free