Start learning free

LESSON 375 OF 404 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: grep v1 — Substring Match in Go

Practice

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

    Grep V1 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