Start learning free

LESSON 2 OF 69 · PROJECTS: COMMAND-LINE TOOLS

cat v2 in Go: Numbered Lines with fmt.Sprintf

Practice Read the full explanation

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

    GO · PROJECTS: COMMAND-LINE TOOLS

    Cat V2 in Go, explained

    Problem overview

    Version 2 adds the -n flag of the cat tool, as a new function: numberedCat(lines []string) string. Each line is preceded by its 1-based line number, right-aligned in a field 6 characters wide, then a tab, then the line text. Lines are still joined with newlines, with none after the last one. Blank lines are numbered too, and an empty slice gives an empty string.

    The previous version already joined lines with \n. This one keeps that loop and changes what is appended for each line.

    Approach: format each row, keep the separator rule

    The loop is the same as before: add a newline before every row except the first. The new work is the row itself, which is made of three parts: the number padded to 6 characters, a tab, and the original line. fmt.Sprintf builds such a string from a pattern, and the verb %6d prints an integer right-aligned in 6 columns, padded with spaces on the left.

    The index i starts at 0, but lines are numbered from 1, so the number passed in is i+1.

    Step by step

    1. Start with an empty result string.
    2. Loop with i from 0 while i < len(lines). The index is used twice: for the number and to pick the line.
    3. Add a newline when i > 0, so rows are separated and none ends the result.
    4. Append the formatted row with fmt.Sprintf("%6d\t%s", i+1, lines[i]). The values follow the pattern in order: the integer for %6d, the string for %s.
    5. Return result after the loop.

    The solution in Go

    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
    }
    

    The Go details:

    • Sprintf returns a string. Unlike Printf, which writes to the output, Sprintf hands back the formatted text, so it can be appended to result. The function needs the fmt import.
    • \t inside the pattern is a real tab. The double-quoted string literal turns the two characters \t into one tab character before Sprintf sees it.
    • %6d pads, it doesn't cut. The width is a minimum. A number with more than 6 digits is printed in full, which pushes that row out of alignment: fmt.Sprintf("%6d\t%s", 1234567, "x") gives "1234567\tx".
    • Arguments must match the verbs. Passing a string where %d expects an integer doesn't stop the build. The output contains an error marker such as %!d(string=...) instead of a number, so check the order of the arguments.

    Tracing

    These results come from running the function (shown as Go string literals):

    numberedCat(["hello", "world", "foo"])
      ->  "     1\thello\n     2\tworld\n     3\tfoo"
    numberedCat(nil)  ->  ""
    

    Printing the result of numberedCat([]string{"hello", "", "foo"}) shows the blank line numbered. The tab character is the gap between the number and the text:

         1	hello
         2	
         3	foo
    

    With 1000 identical lines, the end of the output is "999\tx\n 1000\tx": the wider numbers take more of the 6 columns, so the padding shrinks.

    Edge cases and common mistakes

    • Starting at 0. Passing i instead of i+1 makes the first line number 0.
    • Skipping blank lines. They are numbered like any other line, and a blank line still gets its number and tab.
    • The wrong width. %5d or %-6d changes the alignment: the minus sign left-aligns the number and puts the padding after it.
    • Spaces in place of the tab. The separator is one tab character, not several spaces.
    • A trailing newline. As in the first version, a newline goes between rows only.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free