Start learning free

LESSON 13 OF 70 · PROJECTS: COMMAND-LINE TOOLS

grep in TypeScript: Lines That Contain a Substring

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:

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 lines[i].includes(pattern) is true, then return result.join("\n").

The full solution:
class Solution {
    grep(lines: string[], pattern: string): string {
        let result: string[] = [];
        for (let i = 0; i < lines.length; i++) {
            if (lines[i].includes(pattern)) {
                result.push(lines[i]);
            }
        }
        return result.join("\n");
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    TYPESCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Grep V1 in TypeScript, explained

    Problem overview

    This project lesson builds a tiny grep. The method grep(lines: string[], pattern: string): string returns every line that contains pattern as a substring, in their original order, joined by newline characters. The match is case-sensitive, and when no line matches the result is the empty string.

    With pattern = "err" and lines = ["error: foo", "warning", "another error", "ok"], the result is "error: foo\nanother error". Printed, it is two lines:

    error: foo
    another error

    The pattern is always plain text. Characters such as . or * mean nothing special: they are searched for literally.

    Approach: filter, then join

    The idea has three parts: test each line, collect the ones that pass, and turn the collection into one string. A substring test is exactly what the string method includes does, and it treats its argument as plain text, which is what the lesson wants. The collected lines go into an array, and join("\n") produces the final text.

    Returning one string with newlines between lines, and no newline after the last one, is the reason to collect into an array first. Building the string with += would leave a separator at the start or end that has to be removed. join puts the separator only between two items, so an empty array gives "" and a one-item array gives that item alone.

    Step by step

    1. Create the result. Declare result with let, typed string[], and start it as an empty array. No line has matched yet.
    2. Loop by position. A for loop with i from 0 while i < lines.length visits each line as lines[i].
    3. Test the line. Inside the loop, if (lines[i].includes(pattern)) is true when the pattern appears anywhere in the line, not only at the start.
    4. Keep the line. Inside the if, result.push(lines[i]) adds it to the end of the array. Lines that fail the test are simply skipped.
    5. Join and return. After the loop, result.join("\n") glues the kept lines together with a newline between each pair.

    The solution in TypeScript

    class Solution {
        grep(lines: string[], pattern: string): string {
            let result: string[] = [];
            for (let i = 0; i < lines.length; i++) {
                if (lines[i].includes(pattern)) {
                    result.push(lines[i]);
                }
            }
            return result.join("\n");
        }
    }

    Details that matter in TypeScript:

    • String.prototype.includes is case-sensitive and treats its argument literally. "a.b" as the pattern finds the three characters a, ., b in a row: for ["a.b", "axb"] the result is just "a.b".
    • The type annotation string[] on result matters because an empty array literal has no elements to infer a type from. Writing it makes the intent clear.
    • push changes the array in place and returns the new length, which this code ignores. The variable result itself is never reassigned.
    • join("\n") uses "\n", a single newline character. The result of [].join("\n") is "", which is exactly the "no match" answer, so no special case is needed.

    Complexity

    Each of the m lines is searched once. A substring search costs at most the line length times the pattern length in the worst case, and in practice about the line length. The running time is therefore proportional to the total size of the lines. The result array can hold every line, so the extra space is up to the size of the input.

    Edge cases and common mistakes

    • Case. grep(["Error"], "err") returns "", because "Error" has a capital E. Ignoring case is a different feature.
    • Anywhere in the line. Using startsWith would reject "another error", which contains err in the middle.
    • Special characters. The method does not interpret the pattern, so no escaping is needed. Building a regular expression from the pattern here would turn . into "any character".
    • Trailing newline. Joining with join leaves nothing after the last line. A hand-built string with += line + "\n" would leave a stray newline at the end.
    • Empty input. An empty array, or no matching line, gives "".

    Testing

    linespatternResult
    ["error: foo", "warning", "another error", "ok"]"err""error: foo\nanother error"
    ["error: foo", "warning", "another error", "ok"]"zzz"""
    ["a.b", "axb"]".""a.b"
    ["Error"]"err"""

    The next version builds on this one.

    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free