wc -l Count Looks Wrong? 4 Essential Linux Checks

Your editor shows alpha on line 1 and beta on line 2. You save the file, run wc -l, and get 1. Where did the second line go? Both words can be present. GNU wc -l counts newline characters. When the file ends immediately after the a in beta, only the first row has a terminating newline.

Two paper strips meet at the file boundary where wc -l counts newline characters.

Reproduce the difference with one byte

Run these two commands in a Linux shell. They pass text directly to the counter, so you can try the example without creating or editing a file. The two output columns are newlines and bytes, in that order.

printf 'alpha\nbeta' | wc -l -c
# 1 10
printf 'alpha\nbeta\n' | wc -l -c
# 2 11

Count the first sample by hand. Five letters in alpha, one newline, and four letters in beta make ten bytes. The second command adds exactly one byte. That byte finishes the second line. Using printf here gives you control over whether the sample ends with a newline.

Four wc -l results you can predict

Each \n below represents one line feed (LF). The record count uses the default newline separator in awk.

Newline, byte and record counts for the same ASCII input
Inputwc -lBytesRecords
Empty file000
alpha051
alpha\n161
alpha\n\n272

Inspect the final byte of your file

Replace notes.txt with the path to a plain-text file. Run these read-only commands against the same saved copy you opened in the editor.

wc -l -c < notes.txt
tail -c 1 -- notes.txt | od -An -tx1

The second command takes the final byte and displays it in hexadecimal. This makes an invisible character easier to identify. For the first sample above you would see 61, the final letter a. For the second you would see 0a, a line feed.

  • The last byte is 0a. The file already ends in a newline. If your count still looks low, turn off soft wrapping in the editor and check whether one long line occupies several screen rows.
  • You get another byte. The file contains a trailing fragment after its last line feed, or no line feed at all. An editor can display that fragment as a numbered line.
  • No byte appears. Check the byte count and any error message. A readable, zero-byte file has no final byte. A missing or unreadable file needs a path or access check before its output can tell you anything.

Choose a count that answers your question

Suppose a job expects one label per row, and its last label is valid even if the newline is missing. For an ordinary newline-delimited text file, awk can count that final record. Try both counters on the same input.

printf 'alpha\nbeta' | wc -l
# 1
printf 'alpha\nbeta' | awk 'END { print NR+0 }'
# 2
For alpha and beta without a final newline, wc -l gives one and awk counts two records.

NR is the number of input records read. Adding zero gives a numeric zero on empty input. Blank records count too. If a job accepts only nonblank labels, define that rule explicitly before comparing its total with either command. For CSV with quoted multiline fields, use a CSV reader to count logical records.

How newline and line feed bytes appear in an editor

A final newline and a blank line are different. In alpha\n, the newline finishes the line containing the word. To encode a second, empty line, use alpha\n\n. Some editors put the cursor on a new screen row after a final newline, so the cursor position alone can give the wrong impression.

Windows line endings can change the byte count. A CRLF ending contains a carriage return followed by a line feed. The pair contributes two bytes and one newline to GNU wc. If the newline count matches but the byte total differs, inspect the last two bytes of the saved file.

tail -c 2 -- "notes.txt" | od -An -tx1
Final bytes 61 0a indicate a followed by LF, while 0d 0a indicates CRLF.

For a file ending in the word beta and a Unix newline, expect 61 0a (the letter a followed by LF). A CRLF ending gives 0d 0a. This checks only the end of the file. Earlier lines may use different endings.

Decide whether the file needs a change

If you only need a record count, use the counter that matches your input format. If a consumer requires every line to end in a newline, save a copy with the editor’s final-newline option, then repeat both checks. For a plain LF-delimited file with an unterminated last line, adding just the missing LF increases both counts by one. Appending another LF to an already terminated file creates an empty line.

After saving a copy, run diff -u -- "original.txt" "copy.txt" with your two filenames. Look for the missing-newline marker under the affected line. For help reading the surrounding lines, see how to compare two Linux files with diff.

What happens when two lists are joined?

A missing final newline matters when a second file starts immediately after the first. Suppose the first list holds the labels red and blue, and the second starts with green. Concatenation copies the bytes in order. If blue has no terminating LF, the next label begins on the same line. You still have all the letters, but one record now reads bluegreen. This can explain a missing label even when both individual files look fine in an editor.

{ printf 'red\nblue'; printf 'green\n'; } | awk '{ print NR, $0 }'
# 1 red
# 2 bluegreen
Without a newline at the join, blue and green become a single bluegreen record.

Repeat the command with printf 'red\nblue\n' in the first position. The output now has three numbered records. If your task is to merge lists, check the boundary between inputs before investigating the last byte of the combined result. In both versions of this example the combined stream ends with LF.

A count that passes while the import fails. Suppose a nightly check compares the sum of the two input counts with the count after joining. Here the first stream contains one newline and the second contains one. The joined stream also contains two. The check passes even though the importer reads bluegreen as one label. For an export with one label per row, compare the imported labels with the expected sequence red, blue, green. That check catches the lost boundary.

Why adding one to the count breaks on the next file

It is tempting to put count + 1 into a script after seeing the first example. Apply that shortcut to the empty-file row in the table and it invents a record. Apply it to a file that already ends in LF and every total is one too high. Use the record counter when the final fragment is valid input. Use the newline counter when a complete record must end with LF. If you need to reject an incomplete last record, check the final byte separately and make the handling of empty files explicit.

When reporting the discrepancy, give the file type, newline count, byte count, and final byte. For the first example a colleague could reproduce the issue from one sentence: “The label file contains two labels, ten bytes, one LF, and ends in hex 61.”

Optional lab: trace a count from export to import

A support ticket says an export contains three labels, but a shell check reports two lines. The importer claims to have loaded three rows. Before changing the exporter, establish exactly which quantity each person measured. The small exercises below give you a way to settle that question without access to the original data. All the inputs are invented, and the commands send them through standard input. You can run one exercise at a time.

Choose your starting point. If the discrepancy appears only after a script runs, start with the Bash example. If two exports each look correct on their own, try the boundary test. If a spreadsheet and the terminal disagree, check the CSV example before changing the file.

Read a byte dump from left to right

Try a shorter pair of labels so the entire file fits on one screen. The letters A and B are useful because each occupies one byte in ASCII. The first command displays the bytes that reach the counter. The second command measures the same input.

printf 'A\nB' | od -An -tx1
# 41 0a 42
printf 'A\nB' | wc -l -c
# 1 3

Start at the left and mark each occurrence of 0a. There is exactly one, between the two letters. The last byte is 42. The editor can therefore show a second label even though there is only one completed line. Now predict what you would see if the export ended with two line feeds after B. Write down both totals before running the next command.

printf 'A\nB\n\n' | wc -l -c
# 3 5

The first added byte finishes the line containing B. The second finishes an empty line. If the importer drops empty labels, it may still report two accepted labels. At this point you have three possible totals: five bytes in storage, three newline characters, and two nonempty labels. Which answer belongs in a dashboard depends on what its label promises.

Count populated records when the specification calls for them

Imagine an input form that accepts one product code per row and ignores empty rows. With a blank row between two codes, the newline total alone cannot tell you how many products were supplied. Use a filter that expresses the import rule, then test its behavior on the shortest troublesome input.

printf 'A\n\nB' | awk 'length($0) { n++ } END { print n+0 }'
# 2

This rule treats a row containing a single space as populated. That is a significant choice if someone can paste codes from a worksheet. If whitespace-only rows should also be ignored, test for a character outside the whitespace class instead. The next input contains the code A, a row with a single space, and the code B.

printf 'A\n \nB' | awk '/[^[:space:]]/ { n++ } END { print n+0 }'
# 2

Keep the input rule beside the reported number. A field named “accepted product codes” should follow the importer’s validation rules, which might also reject duplicate or malformed codes. These two commands illustrate the blank-row decision only. Use the importer’s own results if you need the actual count of accepted products.

Check the stream your script really passes to wc -l

A file can be correct on disk and still reach a counter with different bytes. In a common shell mistake, a script captures text using command substitution, then sends the variable to a command. In Bash, command substitution removes trailing newlines. It preserves an internal newline such as the one between A and B. Compare these commands in Bash.

printf 'A\nB\n' | wc -l
# 2
labels=$(printf 'A\nB\n')
printf '%s' "$labels" | wc -l
# 1

The quoted variable keeps the internal separator. The trailing separator has already been removed during assignment. Changing the format to end with a newline would append one, but that would also append one when the original input had none. When your purpose is to measure the original file, redirect the file straight into the counter. If your purpose is to measure an intermediate stream, place the count at the stage whose output you intend to describe.

This difference also explains why pasting a file’s contents into a new terminal command can be a misleading reproduction. A paste operation, a shell variable, and an editor save can each change how the input ends. A small literal generated with an explicit format makes the intended ending visible to the next person investigating the report.

Check whether two files share a record boundary

There is a subtle difference between counting each file separately and counting records after the files are concatenated. Newline counts add up in both cases because concatenation copies the bytes unchanged. Record counts can differ at the join. To see the distinction, let the first file consist of the single letter A and the second contain B followed by LF.

printf 'A' | wc -l
# 0
printf 'B\n' | wc -l
# 1
{ printf 'A'; printf 'B\n'; } | wc -l
# 1

Read separately as records, the inputs contain A and B. Read as a combined stream, they contain the single record AB. The newline totals agree perfectly with the individual totals, so a check based on their sum cannot detect this particular merge error. For a list import, inspect the first record after each join or validate the record format. For a byte-for-byte concatenation, a newly inserted newline would itself be a change to the data.

Check mixed line endings without printing the labels

Sometimes you need to report the shape of a file while keeping its contents private. A final-byte check is useful but leaves a specific question open: could earlier rows use CRLF even if the last one ends with a single LF? The following small example deliberately mixes the two endings. It reports the numbers of records with a trailing carriage return.

printf 'A\r\nB\nC\r\n' | awk '/\r$/ { print NR }'
# 1
# 3

With the default record separator, awk consumes the LF and leaves the preceding carriage return in the record. A match therefore identifies a candidate CRLF row. If the file format permits a literal carriage return as data or ends in a bare CR, inspect the bytes before drawing a conclusion. The last two bytes are conclusive about the end of the sample you inspected. They do not classify every line in the file.

Be careful when comparing byte counts across exports that contain different text. An extra byte per row is consistent with CRLF replacing LF only if the remaining bytes are identical. A change in encoding or a single changed field can alter the byte count as well. Compare short samples with the same known labels before applying a conclusion to a larger export.

Recognize when a physical line is the wrong unit

A CSV export may have a quoted field that spans multiple physical lines. Suppose a row contains a product code and a two-line description. The line break inside the description belongs to the field. It still counts as a newline byte in the file. An ordinary line counter cannot tell from that byte alone whether the CSV record has finished.

printf 'code,description\nA,"top\nbottom"\n' | wc -l
# 3

A CSV reader interpreting that sample sees a header and one data record. Counting newline characters returns three, and subtracting one for the header still gives the wrong data-row total. For spreadsheet exports, use the same delimiter, quoting rules, and header handling as the application that will read the file. Reserve the byte inspection for diagnosing how the file was encoded or terminated.

Write down what would change your diagnosis

If your working explanation is a missing final newline, it makes a concrete prediction. For the same plain-text file and default record separator, the record count should exceed the newline count by one, and the final byte should differ from 0a. An empty file or a file that already ends in LF points you toward a different explanation. Recheck the saved path, wrapping, and the application’s definition of a row.

When two teams disagree over the total, send a small example that keeps the same separators and replaces the original values with A and B. Include the command, its output, the expected result, and the rule that produces that expectation. A report such as “the importer must accept the final label even when its LF is missing” gives the maintainer a specific behavior to test on the next release.

GNU Coreutils manual for wc

Why wc -l can surprise you after joining two files

Suppose two exports contain three color names between them. The first export ends immediately after blue. Run this example in an empty working directory.

printf 'red\nblue' > first.txt
printf 'green\n' > second.txt
awk 'END {print NR}' first.txt second.txt
cat first.txt second.txt | awk '{print NR, $0}'
cat first.txt second.txt | wc -l

Reading the files as separate arguments gives 3 records. Reading the joined stream prints 1 red and 2 bluegreen. Its wc -l count is 2. The join inserted no separator. Once both names have merged, counting the stream with another tool cannot recover their boundary. Count the original files separately when each export defines its own records.

Stay Updated with Kioptrix

Get practical guides, useful resources, and new articles delivered to your inbox.

No spam. Unsubscribe anytime. Read our Privacy Policy.