Skip to Content

Line Numbers

Add or remove line numbers from text. Useful for code snippets, documentation, and text file analysis. Supports custom separators and padding.

Use Cases

  • Code snippets and examples
  • Documentation and tutorials
  • Numbered lists and instructions
  • Log files and debugging
  • Text file analysis

Separator Examples

Dot (.):
1. First line
2. Second line
3. Third line
Parenthesis ():
1) First line
2) Second line
3) Third line
Pipe (|):
1| First line
2| Second line
3| Third line

Key Features

➕ Add Line Numbers

  • Custom starting number
  • Various separator styles
  • Optional padding alignment

➖ Remove Line Numbers

  • Automatic detection
  • Clean removal
  • Preserves original text

🎨 Customization Options

  • Separator: . : | - ) >
  • Starting number
  • Zero-padding alignment

💡 Multiple Use Cases

  • Code documentation
  • Tutorial creation
  • Log file analysis
  • Text file processing

Usage Examples

Basic Line Numbering

Input:

function hello() {
console.log("Hello World");
}

Output (with . separator):

1. function hello() {
2. console.log("Hello World");
3. }

Custom Starting Number

Start from 10:

10. function hello() {
11. console.log("Hello World");
12. }

Different Separators

With : separator:

1: function hello() {
2: console.log("Hello World");
3: }

With ) separator:

1) function hello() {
2) console.log("Hello World");
3) }

With > separator:

1> function hello() {
2> console.log("Hello World");
3> }

With Padding

Aligned with padding:

01. function hello() {
02. console.log("Hello World");
03. }

For larger numbers:

001. Line one
002. Line two
...
099. Line ninety-nine
100. Line one hundred

Programming Language Examples

JavaScript

// Add line numbers
function addLineNumbers(text, start = 1, separator = '. ', padding = false) {
const lines = text.split('\n');
const maxWidth = padding ? String(start + lines.length - 1).length : 0;

return lines.map((line, index) => {
const lineNum = start + index;
const paddedNum = padding
? String(lineNum).padStart(maxWidth, '0')
: lineNum;
return `${paddedNum}${separator}${line}`;
}).join('\n');
}

// Remove line numbers
function removeLineNumbers(text) {
return text.split('\n').map(line => {
return line.replace(/^\d+[.:|\-\)>]\s*/, '');
}).join('\n');
}

// Usage
const code = `function hello() {
console.log("Hello");
}`;

const numbered = addLineNumbers(code, 1, '. ', true);
console.log(numbered);
// 1. function hello() {
// 2. console.log("Hello");
// 3. }

const original = removeLineNumbers(numbered);
console.log(original);

Python

import re

# Add line numbers
def add_line_numbers(text, start=1, separator='. ', padding=False):
lines = text.split('\n')
max_width = len(str(start + len(lines) - 1)) if padding else 0

result = []
for i, line in enumerate(lines):
line_num = start + i
if padding:
padded_num = str(line_num).zfill(max_width)
else:
padded_num = str(line_num)
result.append(f"{padded_num}{separator}{line}")

return '\n'.join(result)

# Remove line numbers
def remove_line_numbers(text):
lines = text.split('\n')
return '\n'.join(re.sub(r'^\d+[.:|\-\)>]\s*', '', line) for line in lines)

# Usage
code = """function hello() {
console.log("Hello");
}"""

numbered = add_line_numbers(code, 1, '. ', True)
print(numbered)

original = remove_line_numbers(numbered)
print(original)

Java

import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class LineNumbers {

// Add line numbers
public static String addLineNumbers(String text, int start,
String separator, boolean padding) {
String[] lines = text.split("\n");
int maxWidth = padding ? String.valueOf(start + lines.length - 1).length() : 0;

return IntStream.range(0, lines.length)
.mapToObj(i -> {
int lineNum = start + i;
String paddedNum = padding
? String.format("%0" + maxWidth + "d", lineNum)
: String.valueOf(lineNum);
return paddedNum + separator + lines[i];
})
.collect(Collectors.joining("\n"));
}

// Remove line numbers
public static String removeLineNumbers(String text) {
Pattern pattern = Pattern.compile("^\\d+[.:|\\-\\)>]\\s*");
return Pattern.compile("\n").splitAsStream(text)
.map(line -> pattern.matcher(line).replaceFirst(""))
.collect(Collectors.joining("\n"));
}

// Usage
public static void main(String[] args) {
String code = "function hello() {\n" +
" console.log(\"Hello\");\n" +
"}";

String numbered = addLineNumbers(code, 1, ". ", true);
System.out.println(numbered);

String original = removeLineNumbers(numbered);
System.out.println(original);
}
}

Best Practices

1. Choose Appropriate Separator

Different separators for different contexts:

  • . - Most common, clear and readable
  • : - Common in log files and technical documentation
  • | - Visual separation, good for tables
  • ) - Markdown-style numbering
  • > - Quote-style, good for scripts

2. Use Padding for Long Files

For files with 100+ lines, use padding for alignment:

001. First line
002. Second line
...
099. Ninety-ninth line
100. One hundredth line

3. Consider Context

Code snippets in documentation:

1. const user = {
2. name: "John",
3. age: 30
4. };

Log file analysis:

1: [INFO] Application started
2: [DEBUG] Loading configuration
3: [ERROR] Connection failed

Tutorial steps:

1) Open the terminal
2) Navigate to project directory
3) Run npm install

4. Remove Before Processing

Remove line numbers before:

  • Compiling code
  • Running scripts
  • Copying to editor
  • Version control commits

5. Preserve Indentation

Ensure line numbers don't affect code indentation:

# Original code indentation preserved
1. def calculate():
2. result = 0
3. for i in range(10):
4. result += i
5. return result

Common Use Cases

1. Code Snippets in Documentation

Here's the implementation:

1. function fibonacci(n) {
2. if (n <= 1) return n;
3. return fibonacci(n - 1) + fibonacci(n - 2);
4. }

Line 2 handles the base case, while line 3 implements recursion.

2. Tutorial Instructions

1) Install Node.js from nodejs.org
2) Open terminal or command prompt
3) Run: npm install -g create-react-app
4) Create new app: create-react-app my-app
5) Navigate: cd my-app
6) Start server: npm start

3. Log File Analysis

1: 2024-01-15 10:30:15 [INFO] Server started
2: 2024-01-15 10:30:16 [DEBUG] Loading config
3: 2024-01-15 10:30:17 [ERROR] Database connection failed
4: 2024-01-15 10:30:18 [INFO] Retrying connection
5: 2024-01-15 10:30:20 [INFO] Connected successfully

4. Code Review Comments

01. public class UserService {
02. private UserRepository repository; // TODO: Add dependency injection
03.
04. public User findUser(Long id) {
05. return repository.findById(id); // FIXME: Handle null case
06. }
07. }

5. Debugging Output

1. def process_data(data):
2. print(f"Input: {data}") # Line 2: Debug input
3. result = transform(data) # Line 3: Transform
4. print(f"Output: {result}") # Line 4: Debug output
5. return result

6. Text File Processing

# Process log file with line numbers
cat application.log | nl -s ': ' > numbered.log

# Search specific line
sed -n '150p' numbered.log

# Extract range
sed -n '100,200p' numbered.log

FAQ

Q: Can I start numbering from a specific number? A: Yes, use the "Starting Number" option to begin from any number.

Q: How do I remove line numbers? A: Switch to "Remove Line Numbers" mode and the tool will automatically detect and remove them.

Q: What separators are supported? A: Common separators include . : | - ) > but you can use any custom separator.

Q: Does padding work with large numbers? A: Yes, padding automatically adjusts based on the highest line number:

001-099: 3 digits
100-999: 4 digits

Q: Will this affect my code indentation? A: No, line numbers are added at the beginning and won't affect existing indentation.

Q: Can I use this for CSV or TSV files? A: Yes, but be careful as adding line numbers adds a column. Consider using : or | as separator for clarity.

Q: How do I copy without line numbers? A: Use the "Remove Line Numbers" mode first, or manually select and copy only the text portion.

Q: Is this useful for version control? A: Line numbers in documentation help when discussing specific code lines in pull requests or issues.