Start learning free

LESSON 364 OF 404 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: cat v2 — Number Lines (-n) in Go

Practice

Now build the -n flag of the cat tool, as a new function. It prints every line preceded by its 1-based line number, right-aligned in 6 columns, then a tab character, then the line text. Blank lines are numbered too, and an empty list gives an empty string.

Function signature:

func numberedCat(lines []string) string

Format per line: the line number right-aligned in a field 6 characters wide (padded with spaces on the left), then a literal tab (\t), then the original line.

Example:

Input: lines = ["hello", "world", "foo"]

Output:
"     1\thello\n     2\tworld\n     3\tfoo"

When printed:
     1	hello
     2	world
     3	foo

Build the result manually: walk through the lines by index and accumulate them into a single string, putting a "\n" before every line except the first.

fmt.Sprintf("%6d\t%s", i+1, lines[i]) formats one entry; %6d right-aligns the integer in 6 columns.

The full solution:
func numberedCat(lines []string) string {
    result := ""
    for i := 0; i < len(lines); i++ {
        if i > 0 {
            result += "\n"
        }
        result += fmt.Sprintf("%6d\t%s", i+1, lines[i])
    }
    return result
}

STEP 1 OF 6
    Ctrl + Enter to check

    Cat V2 in Go

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