Start learning free

LESSON 3 OF 69 · PROJECTS: COMMAND-LINE TOOLS

cat v3 in Go: Showing Tabs and Line Ends (-A)

Practice Read the full explanation

Now build the -A flag of the cat tool, as a new function. It makes whitespace visible: every tab character (\t) is replaced by the two characters ^I and every line ends with a literal $ marker (so trailing spaces become obvious). Lines are then joined with newlines.

Note: real cat -A also shows other control characters (such as ^M) and non-ASCII bytes; this version only handles tabs and line ends, like cat -T -E. A blank line becomes just $, and an empty list gives an empty string.

Function signature:

func showAllCat(lines []string) string

Example:

Input: lines = ["hello\tworld", "foo"]

Output: "hello^Iworld$\nfoo$"

When printed:
hello^Iworld$
foo$

Another example (a blank line, trailing spaces):

Input: lines = ["a\t", "", "x  "]

Output: "a^I$\n$\nx  $"

When printed:
a^I$
$
x  $

Walk each line character by character. When you see a '\t', add "^I" to the transformed line; otherwise add the character itself. After the inner loop, add "$".

Inner transformation:
transformed := ""
for _, c := range line {
    if c == '\t' {
        transformed += "^I"
    } else {
        transformed += string(c)
    }
}
result += transformed + "$"


The full solution:
func showAllCat(lines []string) string {
    result := ""
    for i := 0; i < len(lines); i++ {
        if i > 0 {
            result += "\n"
        }
        line := lines[i]
        transformed := ""
        for _, c := range line {
            if c == '\t' {
                transformed += "^I"
            } else {
                transformed += string(c)
            }
        }
        result += transformed + "$"
    }
    return result
}

STEP 1 OF 13
    Ctrl + Enter to check

    GO · PROJECTS: COMMAND-LINE TOOLS

    Cat V3 in Go, explained

    Problem overview

    Version 3 adds a -A style flag as a new function: showAllCat(lines []string) string. It makes whitespace visible. Every tab character becomes the two characters ^I, every line ends with a literal $ marker, and the lines are joined with newlines. The marker makes trailing spaces easy to spot. A blank line becomes just $, and an empty slice gives an empty string.

    This version handles only tabs and line ends. Other control characters and non-ASCII bytes are left alone. The earlier versions joined lines and numbered them; this one has to look inside each line.

    Approach: rebuild each line character by character

    Joining lines uses the same pattern as before: a newline before every line except the first. What is new is the per-line transformation. For each line, build a new string by visiting its characters one at a time. A tab is replaced by ^I and any other character is copied unchanged. When the line is done, add $ and append the row to the result.

    For ["hello\tworld", "foo"] the result is "hello^Iworld$\nfoo$".

    Step by step

    1. Start with an empty result.
    2. Loop over the lines by position, so the index shows which line is first.
    3. Add a newline when i > 0.
    4. Name the current line line, to keep the following code short.
    5. Create an empty string transformed for the changed line.
    6. Loop over the characters with for _, c := range line. The blank identifier skips the position, which isn't needed.
    7. Replace a tab. If c == '\t', append "^I" to transformed.
    8. Keep everything else. In the else branch, append string(c).
    9. Close the row. After the inner loop, append transformed + "$" to result. This happens once per line, so an empty line still ends with $.
    10. Return result after the outer loop.

    The solution in Go

    func showAllCat(lines []string) string {
    	result := ""
    	for i := 0; i < len(lines); i++ {
    		if i > 0 {
    			result += "\n"
    		}
    		line := lines[i]
    		transformed := ""
    		for _, c := range line {
    			if c == '\t' {
    				transformed += "^I"
    			} else {
    				transformed += string(c)
    			}
    		}
    		result += transformed + "$"
    	}
    	return result
    }
    

    The Go details:

    • range over a string yields runes. The loop decodes the string as UTF-8, and c is a rune (an int32), one Unicode character at a time. The first value, which the code discards with _, is the byte position. Indexing with line[i] would give single bytes instead, which would split a multi-byte character into pieces.
    • Single quotes make a rune, double quotes a string. '\t' is a rune and can be compared with c. "^I" is a string. Comparing a rune with a string, as in c == "\t", doesn't compile.
    • string(c) converts a rune to a string. It produces the UTF-8 text for that character, so transformed += string(c) works for accented letters too. Converting a rune is fine here, but string(someInt) on an ordinary integer is a common source of confusion, since it yields the character with that code, not its digits.
    • if and else in Go need braces and the else goes on the same line as the closing brace.

    Tracing

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

    showAllCat(["hello\tworld", "foo"])  ->  "hello^Iworld$\nfoo$"
    showAllCat(["a\t", "", "x  "])       ->  "a^I$\n$\nx  $"
    showAllCat(nil)                      ->  ""
    showAllCat(["héllo\tü"])             ->  "héllo^Iü$"
    showAllCat(["a\r"])                  ->  "a\r$"
    

    The second row shows both purposes of the marker: the blank line is just $, and the two trailing spaces in "x " show up before the marker. The last two rows show what the function leaves alone. Accented characters pass through intact, and a carriage return stays as it is, because only tabs are replaced.

    Bytes against runes

    The string "é\t" shows why the loop uses range. It has 3 bytes: the letter é takes two bytes in UTF-8 (its first byte is 195) and the tab takes one. Ranging over it yields the rune 233 at byte position 0 and the tab, rune 9, at byte position 2. A loop over line[i] would visit three separate bytes instead, and appending each one as string(line[i]) would turn the two halves of é into two unrelated characters. Since only the tab matters here, a byte loop would still find tabs correctly, but copying the other bytes one by one through string(...) would corrupt non-ASCII text, so the rune loop is the safe habit.

    A shorter way

    The standard library can do the replacement in one call. This version gives the same results as the lesson's loop on the inputs above, such as ["a\t", "", "x "] and an empty slice:

    func showAllShort(lines []string) string {
    	rows := make([]string, len(lines))
    	for i, line := range lines {
    		rows[i] = strings.ReplaceAll(line, "\t", "^I") + "$"
    	}
    	return strings.Join(rows, "\n")
    }
    

    The lesson builds the loop by hand so you practise range, runes and the separator rule, but in everyday code strings.ReplaceAll and strings.Join are the better tools.

    Edge cases and common mistakes

    • Adding $ to the end of the whole result. The marker belongs to every line, so it must be added inside the loop.
    • Dropping blank lines. A blank line still produces a row, consisting of $.
    • Forgetting string(c). transformed += c doesn't compile, because a rune can't be added to a string.
    • Replacing with the tab escape. The replacement is the two visible characters ^ and I, not a tab.
    • Trailing newline. Rows are separated by newlines and the result doesn't end with one.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free