Start learning free

LESSON 13 OF 69 · PROJECTS: COMMAND-LINE TOOLS

grep in Go: Filtering Lines with strings.Contains

Practice Read the full explanation

Build a tiny version of the Unix grep command. Given a list of lines and a search pattern, return all lines that contain pattern as a substring (case-sensitive), joined by newline characters (\n).

Function signature:

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

Example:

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

Output: "error: foo\nanother error"

When printed:
error: foo
another error

If no lines match, return the empty string "".

Note: real grep treats the pattern as a regular expression by default (grep -F matches plain text). Here the pattern is always plain text: just look for it literally, so characters such as . or * mean nothing special.


Iterate over the lines, keep the ones where strings.Contains(line, pattern) is true, then return strings.Join(result, "\n").

The full solution:
func grep(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 6
    Ctrl + Enter to check

    GO · PROJECTS: COMMAND-LINE TOOLS

    Grep V1 in Go, explained

    Problem overview

    The function grep(lines []string, pattern string) string is a tiny version of the Unix grep command. It returns every line that contains pattern as a substring, joined with newline characters (\n). The match is case-sensitive, and the lines keep their original order.

    With pattern = "err" and lines = ["error: foo", "warning", "another error", "ok"], two lines contain err, so the result is "error: foo\nanother error". When nothing matches, the result is the empty string.

    Real grep reads the pattern as a regular expression. Here it is plain text: . and * mean nothing special, and a pattern like "a.b" only matches those three characters in a row.

    Approach

    This is a filter. Walk through the lines, keep the ones that pass a test, and glue the survivors together. The test is a single standard-library call, strings.Contains(line, pattern), which reports whether the first string holds the second anywhere inside it, not only at the start.

    The kept lines go into a slice, and one call to strings.Join turns the slice into the final string. Building the answer by adding "\n" after every line would leave a trailing newline, or an extra one at the front, and would need care at the edges. Join puts the separator only between two items, so a single match gives the line alone, and no match gives "".

    Step by step

    1. Declare the function with the slice of lines and the pattern as parameters, and a string result.
    2. Create an empty slice named result with []string{}. It starts empty because nothing has matched yet.
    3. Loop with range. for _, line := range lines gives each element as line and discards the index with _.
    4. Test the line. if strings.Contains(line, pattern) is true when the pattern appears somewhere in the line.
    5. Keep the line. result = append(result, line) adds it. append returns the grown slice, so the result must be stored back in result.
    6. Join and return. strings.Join(result, "\n") builds the output.

    The solution in Go

    func grep(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")
    }
    

    Go details worth knowing:

    • append may allocate a new array. A slice is a small header that points to an array. When the array is full, append copies the elements into a bigger one and returns a header for it, so calling append(result, line) and ignoring the return value would lose the line.
    • []string{} is empty but not nil. var result []string would also work here: append and strings.Join accept a nil slice, and joining either one gives "".
    • The pattern is literal. strings.Contains does no regular-expression work, so grep(["a.b", "axb", "a*"], "a.b") returns just "a.b", and the pattern "a*" returns just "a*".
    • The returned lines are unchanged. The function doesn't trim or modify them, and lines that are themselves empty are kept when they match.

    Complexity

    Time: O(n * m) in the worst case, where n is the total length of the lines and m the pattern length, since a substring search may compare the pattern at many positions. In practice strings.Contains is much faster than that bound suggests. Space: O(k), where k is the size of the output: the result slice holds the matching lines (as references to the originals), and Join builds one new string of their combined length.

    Edge cases and common mistakes

    • No match. grep(["error: foo", "warning", "another error", "ok"], "xyz") returns "".
    • Case matters. The pattern "Err" doesn't match "error: foo", so that call also returns "". Ignoring case is the next version's job.
    • Empty pattern. Every string contains the empty string, so grep(["x", "y"], "") returns "x\ny".
    • Empty list of lines. The loop doesn't run and the result is "".
    • Special characters. Treating the pattern as a regular expression would make "a.b" match "axb". strings.Contains avoids that.
    • Dropping the stored result of append. The compiler rejects a bare append(result, line) statement with an error that its result is not used.

    Testing

    • ["error: foo", "warning", "another error", "ok"] with "err" gives "error: foo\nanother error".
    • The same lines with "Err" give "".
    • ["a.b", "axb", "a*"] with "a.b" gives "a.b".
    • ["x", "y"] with "" gives "x\ny".
    • [] with "x" gives "".
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free