Start learning free

LESSON 15 OF 70 · PROJECTS: COMMAND-LINE TOOLS

grep -v in TypeScript: Lines That Don't Match

Practice Read the full explanation

Build the -v flag of the Unix grep command. Given a list of lines and a search pattern, return all lines that DO NOT contain pattern as a substring (case-sensitive). Return the remaining lines (the ones that do not contain the pattern), in their original order, joined by newline characters (\n).

Function signature:

grepInvert(lines: string[], pattern: string): string

Example:

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

Output: "ok\nfine"

When printed:
ok
fine

If every line contains the pattern, return the empty string "".


Same as grep v1 but flip the condition: keep the lines where !lines[i].includes(pattern) is true, then return result.join("\n").

The full solution:
class Solution {
    grepInvert(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 V3 in TypeScript, explained

    Problem overview

    This version builds the -v flag of grep, which inverts the match. grepInvert(lines: string[], pattern: string): string returns the lines that do not contain pattern as a substring, in their original order, joined by newline characters. The match is case-sensitive. If every line contains the pattern, the result is "".

    With pattern = "err" and lines = ["error", "ok", "another error", "fine"], the lines "error" and "another error" contain err and are dropped. The result is "ok\nfine".

    Approach: keep the lines where the test is false

    The previous version kept a line when includes(pattern) was true. Inversion needs no new machinery: keep a line when that test is false. In code that is one character, a ! in front of the call. The loop, the result array and the final join stay the same.

    It helps to read the condition aloud: "if the line does not include the pattern, keep it". Everything else, including the order of the lines, follows from the loop visiting them from first to last.

    Step by step

    1. Create the result: an empty string[] named result. The name now holds the lines that were kept, which here are the non-matching ones.
    2. Loop by position with i from 0 while i < lines.length.
    3. Test for absence. if (!lines[i].includes(pattern)) is true when the pattern appears nowhere in the line. The ! flips true into false and false into true.
    4. Keep the line. result.push(lines[i]) inside the if. A line containing the pattern never reaches it.
    5. Join and return with result.join("\n"). If every line was dropped, result is empty and joining it gives "".

    The solution in TypeScript

    class Solution {
        grepInvert(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");
        }
    }

    Language details:

    • ! is the logical NOT operator. It applies to the whole call that follows it, lines[i].includes(pattern), which returns a boolean. No extra parentheses are needed, because a method call binds tighter than !.
    • includes on a string is case-sensitive and compares plain text, so a line such as "Error" does not contain "err" and is therefore kept.
    • An easy alternative is lines.filter(line => !line.includes(pattern)).join("\n"). It does the same thing in one expression, and the loop in the lesson shows each step separately.
    • The method returns a string in every case, including when nothing is kept. [].join("\n") is "", not null or undefined.

    Complexity

    Each of the m lines is searched once, so the time is proportional to the total size of the lines. The result array can hold up to all of them, so the extra space is up to the size of the input.

    Edge cases and common mistakes

    • Forgetting the !. Without it the method is the plain grep and returns the matching lines. For the example it would return "error\nanother error".
    • Everything matches. ["error"] with "err" gives "".
    • Empty list. An empty array gives "" as well.
    • Order. The kept lines stay in their original order, because the loop goes from the first to the last and push appends.
    • Case. The test is case-sensitive, so with the pattern "err" a line like "Error" is not dropped.

    Testing

    linespatternResult
    ["error", "ok", "another error", "fine"]"err""ok\nfine"
    ["error"]"err"""
    []"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