Start learning free

LESSON 14 OF 69 · PROJECTS: COMMAND-LINE TOOLS

grep -i in Go: Case-Insensitive Match with strings.ToLower

Practice Read the full explanation

Build the -i flag of the Unix grep command. Given a list of lines and a search pattern, return all lines that contain pattern as a substring, ignoring letter case. Return the matching lines joined by newline characters (\n).

Function signature:

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

Example:

Input:
pattern = "ERR"
lines = ["Error: 1", "ok"]

Output: "Error: 1"

When printed:
Error: 1

The matching is case-insensitive but the original line (preserving its original casing) is returned. If no lines match, return the empty string "". The lines contain only ASCII characters.


Lowercase the pattern once with strings.ToLower. For each line, check strings.Contains(strings.ToLower(line), lowerPattern) and append the ORIGINAL line on a hit.

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

STEP 1 OF 6
    Ctrl + Enter to check

    GO · PROJECTS: COMMAND-LINE TOOLS

    Grep V2 in Go, explained

    Problem overview

    The function grepCaseInsensitive(lines []string, pattern string) string is the -i flag of Unix grep. It returns the lines that contain pattern as a substring, ignoring letter case, joined by \n. The lines come back exactly as they were given, capitals and all.

    With pattern = "ERR" and lines = ["Error: 1", "ok"], the result is "Error: 1": the pattern ERR matches the start of Error once case is ignored, and the line keeps its original spelling. If no line matches, the result is "". The lines contain only ASCII characters.

    Approach

    The previous version used strings.Contains(line, pattern), which is case-sensitive. To ignore case, compare both sides in the same case. Lowercase the pattern, lowercase the line, and ask Contains about the two lowercase strings. "ERR" becomes "err", "Error: 1" becomes "error: 1", and the match is found.

    Two details shape the solution:

    • The pattern is the same for every line, so it is lowercased once, before the loop, not again on each pass.
    • The lowercase text is only used for the test. What goes into the result is the original line. Go strings are immutable, so strings.ToLower doesn't change anything: it returns a new string, and the original stays as it was.

    Step by step

    1. Create the empty result slice for the lines that match.
    2. Lowercase the pattern once. lowerPattern := strings.ToLower(pattern) is computed before the loop.
    3. Loop over the lines with for _, line := range lines.
    4. Compare in lowercase. strings.Contains(strings.ToLower(line), lowerPattern) lowercases a copy of the line and looks for the lowercase pattern in it.
    5. Append the original line, not the lowercase copy, and store the grown slice back in result.
    6. Join with newlines and return. Joining an empty slice gives "", the answer when nothing matched.

    The solution in Go

    func grepCaseInsensitive(lines []string, pattern string) string {
        result := []string{}
        lowerPattern := strings.ToLower(pattern)
        for _, line := range lines {
            if strings.Contains(strings.ToLower(line), lowerPattern) {
                result = append(result, line)
            }
        }
        return strings.Join(result, "\n")
    }
    

    Go details to notice:

    • Strings are immutable. A call like strings.ToLower(line) on its own line would do nothing useful, because the lowercase text is the return value. The code uses that value directly inside the if and never assigns it back to line, which is why result receives the original text.
    • Which variable gets appended matters. append(result, line) keeps "Error: 1". Appending the lowercase copy would return "error: 1", and the lesson's tests would fail.
    • Unicode. ToLower handles non-ASCII letters too, but the lesson's input is ASCII, so only that case matters here.

    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. Lowercasing each line costs time proportional to its length, and the substring search adds to it. Space: O(L + k), where L is the length of the longest line, for the temporary lowercase copy, and k is the size of the output.

    Edge cases and common mistakes

    • Returning the lowercase line. For ["Error: 1", "ok", "WARN err", "fine"] and the pattern "eRr", the result is "Error: 1\nWARN err", with the original capitals.
    • Lowercasing only one side. If only the line is lowercased, an uppercase pattern like "ERR" can never match. If only the pattern is lowercased, a line like "Error" can't match either. Both sides need the same case.
    • Same lines, case-sensitive version. grep(["Error: 1", "ok"], "ERR") from the previous version returns "", while the case-insensitive version returns "Error: 1".
    • No match. With ["Error: 1", "ok"] and the pattern "zzz" the result is "".
    • Non-letters. Digits and punctuation have no case, so strings.ToLower("ABC-1") is "abc-1": only the letters change.

    Testing

    • ["Error: 1", "ok"] with "ERR" gives "Error: 1".
    • ["Error: 1", "ok", "WARN err", "fine"] with "eRr" gives "Error: 1\nWARN err".
    • ["Error: 1", "ok"] with "zzz" 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