Need to count lines in text programmatically? This guide covers everything you need to know about line counting via API, including handling different newline formats and blank lines.
What is Line Counting?
Line counting determines the number of lines in a text document. This is useful for code analysis, log processing, and document metrics. Accurate line counting must handle different newline characters and decide whether to count blank lines.
Example: A text with content on 3 lines separated by newlines has a line count of 3.
Understanding Newline Formats
Different operating systems use different newline characters:
- Unix/Linux/macOS: LF (
\n) - Windows: CRLF (
\r\n) - Classic Mac: CR (
\r)
Using the Line Count API
TinyFn provides a simple endpoint to count lines:
POST https://api.tinyfn.io/v1/text/line-count
Headers: X-API-Key: your-api-key
Content-Type: application/json
{
"text": "Line one\nLine two\nLine three"
}
{
"total_lines": 3,
"non_empty_lines": 3,
"empty_lines": 0
}
Parameters
| Parameter | Type | Description |
|---|---|---|
text |
string | The text to analyze (required) |
skip_empty |
boolean | Exclude empty lines from count (default: false) |
Code Examples
JavaScript / Node.js
const response = await fetch(
'https://api.tinyfn.io/v1/text/line-count',
{
method: 'POST',
headers: {
'X-API-Key': 'your-api-key',
'Content-Type': 'application/json'
},
body: JSON.stringify({ text: 'Line one\nLine two\nLine three' })
}
);
const result = await response.json();
console.log(result.total_lines); // 3
Python
import requests
response = requests.post(
'https://api.tinyfn.io/v1/text/line-count',
headers={'X-API-Key': 'your-api-key'},
json={'text': 'Line one\nLine two\nLine three'}
)
result = response.json()
print(result['total_lines']) # 3
cURL
curl -X POST "https://api.tinyfn.io/v1/text/line-count" \
-H "X-API-Key: your-api-key" \
-H "Content-Type: application/json" \
-d '{"text": "Line one\nLine two\nLine three"}'
Common Use Cases
- Code Analysis: Count lines of code (LOC) for metrics
- Log Processing: Determine log file sizes
- Document Metrics: Track document length over time
- Data Validation: Verify expected row counts in CSV/TSV
- File Comparison: Quick comparison of file lengths
Best Practices
- Handle all newlines: Support LF, CRLF, and CR formats
- Decide on blanks: Be consistent about counting empty lines
- Normalize input: Consider normalizing newlines before counting
- Report both: Return total and non-empty line counts
Use via MCP
Your AI agent can call this tool directly via Model Context Protocol — no HTTP code needed. Add TinyFn to Claude Desktop, Cursor, or any MCP client:
{
"mcpServers": {
"tinyfn-text": {
"url": "https://api.tinyfn.io/mcp/text/",
"headers": {
"X-API-Key": "your-api-key"
}
}
}
}
See all text analysis tools available via MCP in our Text Analysis MCP Tools for AI Agents guide.