Count Lines in Text — Total, Blank, and Non-Blank
Count total, blank, and non-blank lines in any text. Learn how line counting works across different operating systems, line ending formats (LF vs CRLF), and common line counting use cases in programming.
Detailed Explanation
Line Counting
Line counting is a fundamental text metric used across programming, writing, and data processing. A "line" is any sequence of characters terminated by a newline character.
Basic Line Count
function countLines(text) {
if (!text) return { total: 0, blank: 0, nonBlank: 0 };
const lines = text.split(/\r?\n/);
const blank = lines.filter(l => l.trim() === "").length;
return {
total: lines.length,
blank: blank,
nonBlank: lines.length - blank,
};
}
The regex /\r?\n/ handles both Unix (\n) and Windows (\r\n) line endings.
Line Ending Formats
Different operating systems use different newline conventions:
| Format | Characters | Escape | Platform |
|---|---|---|---|
| LF | Line Feed | \n |
Unix, macOS, Linux |
| CRLF | Carriage Return + Line Feed | \r\n |
Windows |
| CR | Carriage Return | \r |
Classic Mac OS (pre-X) |
Modern practice is converging on LF (\n), but CRLF is still common in Windows environments and many protocols (HTTP, SMTP, CSV).
Trailing Newline Behavior
A subtle question: does a file ending with \n have an extra blank line?
"hello\nworld\n" → 2 lines or 3?
Most text editors and wc -l count this as 2 lines — the trailing newline is a line terminator, not a separator. JavaScript's split("\n") on "hello\nworld\n" returns 3 elements (the third being empty), so you may need to adjust:
// Handle trailing newline
const lines = text.split(/\r?\n/);
if (lines[lines.length - 1] === "") lines.pop();
Lines of Code (LOC)
In software development, line counts are a common (if imperfect) metric:
- Physical LOC — total lines in the file
- Logical LOC — lines containing actual statements (excluding blank lines and comments)
- SLOC — Source Lines of Code (non-blank, non-comment lines)
Use in Data Processing
Line counting is essential for:
- CSV files — line count minus 1 gives the number of data rows
- Log files — line count represents the number of log entries
- Configuration files — tracking complexity and size
- Diff outputs — counting added/removed lines for code review metrics
Use Case
Developers count lines of code for project metrics and complexity estimation. Data engineers verify CSV row counts before and after transformations. DevOps engineers monitor log file line counts for anomaly detection, and writers use line counts when working with fixed-format outputs like poetry, screenplays, or formatted reports.