Table of Contents
Back to Blog

Cross-Platform Guide

How to Count Lines in a File on Linux, macOS, and Windows

Count lines in any file on Linux, macOS, or Windows using wc -l, PowerShell, CMD, and GUI tools. Includes large file methods, CSV row counting, and cross-platform scripts.

LinuxmacOSWindows
Published: March 20, 2025Updated: May 12, 202618 min readAuthor: Line Counter Editorial Team
LinuxmacOSWindowsPowerShellCLI

You are switching between a Linux server, a MacBook, and a Windows machine. You need to count lines in a log file.

On Linux, you type wc -l app.log without thinking. On macOS, the same command works, but the output padding can look different. On Windows, you open PowerShell and the Unix habit no longer applies.

This guide gives you the right command for each platform, explains why the commands differ, and ends with cross-platform scripts that work everywhere. It is the hub page for terminal-based line counting: Linux, macOS, Windows, CSV files, compressed logs, and GUI alternatives for people who do not want the terminal at all.

Use it when you need to count lines in a file once, document the command for a teammate, or choose a method that works across operating systems.

If you want deeper shell behavior, read the Bash line counting guide. If you want to script the solution, the Python cross-platform solution and Node.js line counting guides go further.

Three-Platform Quick Answer

Quick commands

Linux

macOS

Windows

For most people, that table is enough. The rest of the guide explains how to count lines in a file when edge cases matter: missing trailing newlines, filenames with spaces, large files, CSV rows, and Windows users who prefer GUI tools.

The important difference is platform fit. Count lines linux workflows are fastest with Unix text tools, count lines mac workflows need BSD/GNU awareness, and count lines windows workflows are usually best in PowerShell.

If your goal is simply to count lines in a file and move on, pick the command for your platform from the quick card and skip the edge-case sections.

Part 1: Count Lines in a File on Linux

Linux conclusion

For count lines linux workflows, use wc -l for speed and use awk when files may not end with a newline.

1A. wc -l basics

The standard Linux command is:

wc -l file.txt

Output:

42 file.txt

If you only want the number:

wc -l < file.txt

wc without options prints three counts:

$ wc file.txt
  42  387  2341 file.txt
   |    |     |    |
 lines words bytes filename

Use wc -l when the question is simply "how do I count lines in a file quickly?"

For count lines linux tasks on servers, this is the command most developers expect to see in runbooks and incident notes.

Multiple files:

wc -l *.log

Recursive directory count with safe filename handling:

find . -type f -name "*.txt" -print0 | xargs -0 wc -l

The -print0 and -0 pair matters because filenames can contain spaces. This is the reliable version of the common find . | xargs wc -l pattern.

That safe form is the better default for count lines linux scripts that walk real project folders.

For count lines linux jobs that run in CI, always keep the -print0 form unless you fully control every filename.

1B. awk for missing trailing newlines

wc -l counts newline characters. If a file contains line1\nline2 with no final newline, wc -l reports 1 even though many editors show two logical lines.

Use awk when that matters:

awk 'END{print NR}' file.txt

Other useful awk patterns:

awk 'NF' file.txt | wc -l
awk '/ERROR/{count++} END{print count}' app.log

1C. grep for filtered line counts

grep -c '' file.txt
grep -c '.' file.txt
grep -c "ERROR" app.log
grep -cv "DEBUG" app.log

grep -c '' counts all lines. grep -c . counts non-empty lines. That difference matters when blank lines are part of the file.

1D. sed for the last line number

sed -n '$=' file.txt

This prints the last line number, which is the total line count. It is not usually faster than wc -l, but it is useful in scripts that already use sed.

Linux method comparison

Method100MB file1GB fileMissing trailing newlineBest use
wc -l fileabout 0.18sabout 1.8sCounts newline bytesDaily quick check
wc -l < fileabout 0.18sabout 1.8sCounts newline bytesScript-friendly output
awk 'END{print NR}'about 0.38sabout 3.8sCounts final unterminated lineAccuracy
grep -c ''about 0.42sabout 4.2sCounts final unterminated lineAccuracy
sed -n '$='about 0.51sabout 5.1sCounts final unterminated linesed-heavy scripts

The numbers are directional Linux SSD measurements, not promises. The stable rule is that wc -l is fastest and awk is safer for logical lines.

Part 2: Count Lines in a File on macOS

macOS platform note

macOS uses BSD wc while most Linux distributions use GNU wc. The common syntax is the same, but output padding and less-common options can differ.

The basic count lines mac command is the same as Linux:

wc -l file.txt

For a script-friendly number:

wc -l < file.txt | tr -d ' '

Or avoid wc formatting entirely:

awk 'END{print NR}' file.txt

This matters for count lines macos scripts because wc output may include leading spaces. Numeric shell comparisons usually handle that, but string output and JSON generation can look messy.

If your team writes count lines mac automation for both local laptops and Linux CI, prefer awk for the final number.

CommandLinux stylemacOS BSD style
wc -l file.txtpadded count plus filenamepadded count plus filename
wc -l < file.txtcount, often with little paddingcount, commonly with padding
awk 'END{print NR}' file.txtplain numberplain number

If you want GNU versions on macOS:

brew install coreutils
gwc -l file.txt

You can alias wc=gwc, but be cautious in shared scripts. It is usually better to write commands that work with both BSD and GNU tools.

macOS GUI note: Finder and TextEdit show file size and text content, but not newline-delimited line counts. For a free GUI, VS Code is the better option; see the count lines in VS Code guide.

Part 3: Count Lines in a File on Windows

Windows conclusion

For count lines windows workflows, use PowerShell first. CMD works for quick checks, but PowerShell is clearer, more scriptable, and better for large files.

3A. PowerShell

The simplest powershell count lines command is:

(Get-Content "file.txt").Count

Short alias version:

(gc "file.txt").Count

Pipeline version:

(Get-Content "file.txt" | Measure-Object -Line).Lines

The pipeline form is useful when the content is already flowing through other commands. Microsoft documents Get-Content as the cmdlet for reading file contents and Measure-Object as the cmdlet for counting lines, words, and characters.

For powershell count lines snippets in documentation, show both the short version and the Measure-Object version so readers know which one is script-friendly.

For large files, use chunked reading:

$count = 0
Get-Content "large-file.txt" -ReadCount 1000 | ForEach-Object {
    $count += $_.Count
}
$count

For very large files, use .NET StreamReader:

$reader = [System.IO.StreamReader]::new("C:\path\to\file.txt")
$count = 0
try {
    while ($reader.ReadLine() -ne $null) { $count++ }
}
finally {
    $reader.Close()
}
$count

PowerShell method comparison:

Method100MB file1GB fileMemoryBest use
(gc file).Countabout 2.1sCan be memory-heavyHighSmall files
`gcMeasure-Object -Line`about 1.8sabout 18sModerate
StreamReaderabout 0.9sabout 9sLowLarge files

These are directional Windows SSD timings. Always benchmark on the machine that will run the job.

For count lines windows scripts, the main tradeoff is convenience versus memory: (Get-Content file).Count is simple, while StreamReader is the large-file option.

If you want the full PowerShell version with -ReadCount, -Raw, Measure-Object -Line, and .NET API details, see the dedicated PowerShell line counting guide.

If you need powershell count lines behavior for scheduled jobs, prefer Measure-Object or StreamReader over loading the whole file into an array.

3B. CMD

CMD does not have a direct wc -l equivalent. The usual workaround is:

find /c /v "" file.txt

Typical output:

---------- FILE.TXT: 42

To echo only the count:

for /f "tokens=3" %a in ('find /c /v "" file.txt') do echo %a

Inside a batch file, double the percent signs:

for /f "tokens=3" %%a in ('find /c /v "" file.txt') do set count=%%a
echo Total lines: %count%

CMD is awkward because it was not designed as a strong text-processing shell. find /c /v "" is a workaround: /c prints a count and /v counts lines that do not contain the search string. For robust Windows scripts, use PowerShell.

Use CMD only when count lines windows instructions must work on locked-down machines where PowerShell scripts are not allowed.

3C. Windows GUI options

For non-technical users who want to count lines without opening file content in a terminal, use a GUI editor.

This is the practical count lines windows path for users who do not want shell commands at all.

Notepad++:

1. Open the file in Notepad++.
2. Press Ctrl+End to jump to the last line.
3. Read the Ln value in the status bar.
4. Or use View -> Summary for file statistics.

Excel for simple CSV files:

1. Import the CSV into Excel.
2. Press Ctrl+End.
3. Read the final row number.
4. Subtract 1 if the first row is a header.

Word:

Review -> Word Count -> Lines

Word counts visual layout lines, not newline-delimited logical lines. Use it for documents, not logs or code.

VS Code:

1. Open the file in VS Code.
2. Clear any selection.
3. Read the total line count in the status bar.

VS Code is free and precise for text files. For details, see count lines in VS Code. For no-install browser workflows, use the online line counter.

3D. Windows Subsystem for Linux

If WSL is installed, you can use Linux commands from Windows:

wsl wc -l /mnt/c/path/to/file.txt

Or enter WSL first:

wsl
wc -l /mnt/c/Users/username/Documents/file.txt

This is useful for developers who already use Linux tooling on Windows.

Part 4: Cross-Platform Line Counting

4A. Python script

Use Python when you need one script for Linux, macOS, and Windows:

#!/usr/bin/env python3
import sys
from pathlib import Path

def count_lines(filepath: str) -> int:
    path = Path(filepath)
    if not path.exists():
        print(f"Error: File not found: {filepath}", file=sys.stderr)
        sys.exit(1)

    if path.stat().st_size == 0:
        return 0

    if path.stat().st_size > 100 * 1024 * 1024:
        with path.open("rb") as f:
            count = sum(chunk.count(b"\n") for chunk in iter(lambda: f.read(1 << 20), b""))
            f.seek(-1, 2)
            if f.read(1) != b"\n":
                count += 1
        return count

    with path.open(encoding="utf-8", errors="replace") as f:
        return sum(1 for _ in f)

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python count_lines.py <file>")
        sys.exit(1)
    print(f"{count_lines(sys.argv[1]):,} lines")

This is the most practical cross-platform answer when you need count lines without opening file content manually. The Python cross-platform solution guide explains the chunk-scan edge cases in more detail.

4B. Node.js script

#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const readline = require('readline');

async function countLines(filePath) {
  if (!filePath) {
    console.error('Usage: node count_lines.js <file_path>');
    process.exit(1);
  }

  const resolved = path.resolve(filePath);

  if (!fs.existsSync(resolved)) {
    console.error(`Error: File not found: ${filePath}`);
    process.exit(1);
  }

  return new Promise((resolve, reject) => {
    let count = 0;
    const rl = readline.createInterface({
      input: fs.createReadStream(resolved),
      crlfDelay: Infinity,
    });

    rl.on('line', () => count++);
    rl.on('close', () => resolve(count));
    rl.on('error', reject);
  });
}

countLines(process.argv[2]).then((count) => {
  console.log(`${count.toLocaleString()} lines`);
});

The crlfDelay: Infinity option keeps Windows \r\n line endings from being misread. The Node.js line counting guide covers more browser and stream cases.

4C. Cross-platform command table

TaskLinuxmacOSWindows PowerShell
Single filewc -l filewc -l file(gc file).Count
Number onlywc -l < filewc -l < file | tr -d ' '(gc file | measure -l).Lines
Non-empty linesgrep -c . filegrep -c . file(gc file | ? Length).Count
Matching linesgrep -c "str" filegrep -c "str" file(sls "str" file).Count
Recursive directoryfind . -print0 | xargs -0 wc -lfind . -print0 | xargs -0 wc -l(gci -r -File | gc).Count
Script variablen=$(wc -l < file)n=$(awk 'END{print NR}' file)$n=(gc file | measure -l).Lines

Which Method Should You Use?

Where are you?
|
+-- Linux
|   +-- Quick count -> wc -l
|   +-- Missing trailing newline matters -> awk 'END{print NR}'
|
+-- macOS
|   +-- Quick count -> wc -l
|   +-- Script output must be clean -> awk 'END{print NR}'
|   +-- Want GNU behavior -> brew install coreutils, then gwc
|
+-- Windows
    +-- Comfortable with PowerShell -> (gc file).Count
    +-- Very large file -> StreamReader
    +-- CMD only -> find /c /v "" file.txt
    +-- No terminal -> Notepad++, VS Code, or Line Counter

Part 5: Counting Lines in Specific File Types

5A. CSV files

For simple CSV files, line count is easy:

If your search is count lines csv file, first decide whether you mean physical lines or data rows.

wc -l < data.csv
echo $(($(wc -l < data.csv) - 1))

That subtracts one header row. But count lines csv file workflows can be tricky because CSV fields can contain embedded newlines:

id,note
1,"hello
world"
2,"ok"

The file has more physical lines than data rows. Use a CSV parser for accuracy:

python3 -c "import csv; print(sum(1 for _ in csv.reader(open('data.csv', newline=''))) - 1)"

Windows PowerShell:

(Import-Csv "data.csv").Count

For quick browser checks, use the online line counter or the main Line Counter tool.

For count lines csv file work outside a terminal, a browser or spreadsheet is often safer than raw line counting.

5B. Log files

echo "ERROR:   $(grep -c 'ERROR' app.log)"
echo "WARNING: $(grep -c 'WARNING' app.log)"
echo "INFO:    $(grep -c 'INFO' app.log)"
grep "2026-05-12" app.log | wc -l
tail -1000 app.log | grep -c "ERROR"

These are not just line counts. They are filtered operational metrics.

5C. Compressed files

zcat file.gz | wc -l
bzcat file.bz2 | wc -l
xzcat file.xz | wc -l
unzip -p archive.zip file.txt | wc -l

macOS may require gzcat instead of zcat depending on your shell environment and installed tools.

FAQ

How do I count lines in a file on Linux?

Use wc -l file.txt. It prints the line count and filename. Use wc -l < file.txt when you need only the number.

How do I count lines in a file on Mac?

Use wc -l file.txt in Terminal. For script-safe output, use awk 'END{print NR}' file.txt or pipe wc output through tr -d ' '.

How do I count lines in a file on Windows?

Use PowerShell: (Get-Content "file.txt").Count. For large files, use the StreamReader loop in Part 3.

How do I count lines in a file using CMD?

Use find /c /v "" file.txt. The output includes the filename and formatting, so PowerShell is better for scripting.

How do I count lines in a CSV file?

For simple CSV files, use wc -l and subtract one header row. For CSV files with embedded newlines, use Python's csv.reader or PowerShell Import-Csv.

What is the difference between wc -l on Mac and Linux?

Linux usually uses GNU wc; macOS uses BSD wc. The common wc -l syntax works on both, but output padding and some option details differ.

How do I count lines without opening the file?

Use a terminal command such as wc -l, PowerShell Get-Content, CMD find, or a script. These count lines without opening the file in an editor.

How do I count lines in a large file?

On Linux and macOS, wc -l is usually the fastest raw count. On Windows, use a .NET StreamReader loop. For cross-platform automation, use the Python binary chunk script.

Is there a cross-platform way to count lines?

Yes. Use the Python or Node.js script in Part 4, or use the browser-based Line Counter tool when you do not want a terminal.

Sources Checked

Do Not Want to Use the Terminal?

If you just need to count lines in a file right now, no commands, no installs, no platform differences, paste the content or upload the file to the Line Counter. It works the same on Linux, Mac, and Windows because it runs in your browser.

Quick CTA

Need to count lines without opening the terminal? Use the Line Counter tool for instant line, blank-line, and non-empty-line counts.

Frequently Asked Questions

How do I count lines in a file on Linux?

Use wc -l file.txt for a human-readable result or wc -l < file.txt for a script-friendly number. Use awk 'END{print NR}' when a missing trailing newline must still count as a line.

How do I count lines in a file on Mac?

Use wc -l file.txt or wc -l < file.txt in Terminal. macOS uses BSD wc, so output padding can differ from Linux; normalize script values with awk or tr.

How do I count lines in a file on Windows?

Use PowerShell: (Get-Content file.txt).Count for small files, (Get-Content file.txt | Measure-Object -Line).Lines for pipeline output, or StreamReader for very large files.

How do I count lines in a file using CMD?

Use find /c /v "" file.txt. CMD has awkward output and weaker text-processing tools than PowerShell, so PowerShell is recommended for scripts.

How do I count lines in a CSV file?

Use wc -l minus one for simple CSV files with a header. If fields can contain embedded newlines, use Python's csv module or PowerShell Import-Csv instead.

What is the difference between wc -l on Mac and Linux?

Linux normally uses GNU wc, while macOS uses BSD wc. The syntax is the same for common line counts, but output padding and some option behavior can differ.

How do I count lines without opening the file?

All terminal methods in this guide count lines without opening the file in an editor. Use wc -l, PowerShell, CMD find, Python, or Node.js depending on your platform.

How do I count lines in a large file?

On Linux or macOS, wc -l is usually fastest for raw line counts. On Windows, use a .NET StreamReader loop. For cross-platform scripts, use Python binary chunk scanning.

Is there a cross-platform way to count lines?

Yes. Use the Python or Node.js scripts in Part 4, or use the browser-based Line Counter tool for a no-code workflow.

Related Guides