Start learning free

LESSON 15 OF 70 · PROJECTS: COMMAND-LINE TOOLS

grep -v in Kotlin: 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:

fun grepInvert(lines: Array<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 !line.contains(pattern) is true, then return result.joinToString("\n").

The full solution:
class Solution {
    fun grepInvert(lines: Array<String>, pattern: String): String {
        val result = mutableListOf<String>()
        for (line in lines) {
            if (!line.contains(pattern)) {
                result.add(line)
            }
        }
        return result.joinToString("\n")
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    KOTLIN · PROJECTS: COMMAND-LINE TOOLS

    Grep V3 in Kotlin, explained

    Problem overview

    This version adds the -v flag, which inverts the match. The function grepInvert(lines: Array<String>, pattern: String): String returns every line that does not contain pattern as a substring. The test is case-sensitive, the surviving lines keep their original order, and they are joined by newline characters. If every line contains the pattern, the result is the empty string.

    With pattern = "err" and lines = ["error", "ok", "another error", "fine"] the result is "ok\nfine". Printed:

    ok
    fine
    

    Approach: flip the test

    Version 1 of grep kept the lines where contains was true. This version keeps the lines where it is false. The loop, the result list and the join stay the same, and the only change is a ! in front of the condition. That is the whole idea of the lesson.

    One thing is new on the surface: the parameter is an Array<String> instead of a List<String>. For this function it makes no difference to the body, because a for loop works over both. It only matters to whoever calls the function, which is why the examples below use arrayOf.

    Step by step

    1. Create the result list. mutableListOf<String>() in a val named result collects the lines to keep.
    2. Loop over the lines with for (line in lines) and close the brace right away.
    3. Negate the check. Inside the loop, the if uses ! in front of line.contains(pattern). The condition is now true exactly when the pattern is absent.
    4. Keep the line. Inside the if, result.add(line) stores it. Only a line without the pattern gets here.
    5. Join and return. result.joinToString("\n") builds the answer. If every line contained the pattern, nothing was kept, and joining an empty list gives the empty string the task asks for.

    The solution in Kotlin

    class Solution {
        fun grepInvert(lines: Array<String>, pattern: String): String {
            val result = mutableListOf<String>()
            for (line in lines) {
                if (!line.contains(pattern)) {
                    result.add(line)
                }
            }
            return result.joinToString("\n")
        }
    }
    

    Kotlin details to know:

    • ! is the logical NOT operator. It turns a Boolean into its opposite, so !line.contains(pattern) reads as "the line doesn't contain the pattern". The ! applies to the whole call, because the call binds tighter than the operator.
    • Array<String> and List<String> are different types. A function that takes an Array<String> can't be called with listOf("a"): the compiler reports that the actual type is List<String> but Array<String> was expected. Build the argument with arrayOf("a", "b"), or turn a list into an array with toTypedArray().
    • The result is still a MutableList, even though the input is an array, since the array's size can't change but the list needs to grow.
    • joinToString("\n") puts the separator between items only, so there is no newline after the last line.

    Edge cases and common mistakes

    • Case still matters. With pattern "err", the line "Err" doesn't contain it, so it is kept: ["Err", "ok"] returns both lines.
    • Substrings anywhere. "xerr" contains "err" in the middle, so it is dropped.
    • Nothing to remove. If no line contains the pattern, every line comes back, in the original order.
    • Everything removed. The result is "", with no stray newline.
    • Forgetting the !. Without it the function is the first version of grep and returns the opposite set of lines.

    Testing

    These results come from running the reference solution on arrays:

    linespatternresult
    ["error", "ok", "another error", "fine"]"err"ok and fine, on two lines
    ["error", "xerr"]"err"the empty string
    ["a", "b"]"z"a and b, on two lines
    ["Err", "ok"]"err"Err and ok, on two lines
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free