Start learning free

LESSON 612 OF 671 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: grep v2 — Case-Insensitive Match

Practice

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