Text encodings, bytes and line endings
Quick answer
A text file contains bytes interpreted using an encoding. UTF-8 represents ASCII letters with one byte and many other characters with multiple bytes. A line ending is also stored as bytes. Knowing this explains why file sizes, character counts and line counts can differ.
Prepare the practice environment
Use the chapter fixture described in lab-fixtures/text-streams/README.md. Run setup as a normal user in a disposable Linux environment, enter the printed directory and check pwd. Every example assumes a fresh fixture. Commands omit the terminal prompt; outputs below are not commands.
How it works
wc -c counts bytes; wc -m counts characters according to the active locale; wc -l counts newline bytes, not necessarily every visually apparent line. A visible grapheme may consist of several Unicode code points. Linux text commonly uses LF (hex 0a); Windows-style text often uses CRLF (0d 0a). UTF-8 and CRLF are independent properties. od -An -tx1 displays hexadecimal bytes without addresses. The lab uses Debian’s C.utf8 locale for UTF-8 examples; verify locale -a on your own distribution and select an available UTF-8 locale. A file with no final LF can have one visible line but a zero newline count.
For a file containing the ASCII letter x and CRLF, there are three bytes but only one LF. Replacing CRLF with LF changes the bytes without changing the newline count. Use byte inspection when a display hides the difference; do not convert every file indiscriminately, especially binary files.
Try the examples
LC_ALL=C.utf8 wc -c < utf8.txtLC_ALL=C.utf8 wc -m < utf8.txtThe fixture contains two Persian letters (each two bytes in UTF-8) and LF. There are five bytes and three characters. < passes the file as input, so wc prints counts without a filename; redirection is covered fully in lesson 5.
Expected stdout:
53Both files contain x; the second has an extra CR byte before LF. Spaces in od output are formatting.
Expected stdout:
78 0a78 0d 0aThe file contains x without LF. Zero is correct even though a text editor may display one line.
Expected stdout:
0Common mistakes
Do not assume wc -c equals the number of characters. Do not blindly remove every CR from arbitrary data to fix line endings: CR may be meaningful. Preserve originals and use an appropriate conversion tool on a copy when needed.
Practice
Compare wc -c and wc -l for lf.txt and crlf.txt. Explain why both contain one newline but have different byte counts.
Related references
Study: wc, od. These are reference names, not deployed links.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Text encodings and line endings — Knowledge Check
Apply the lesson concepts to the controlled text fixture.
What does wc -c count?
Which hex bytes represent CRLF?
Why may wc -l return 0 for a nonempty file?
What affects wc -m interpretation?