SysTutorials

Adding a Prefix to Each Line in Bash

· updated April 12, 2026

Several methods exist to prepend a prefix string to each line of text. The right approach depends on your input source and performance requirements.

Using sed

The sed stream editor is the most portable and efficient approach:

sed 's/^/PREFIX/' file.txt

This uses a substitution command where ^ matches the start of each line and PREFIX is your desired prefix. To save output back to the file:

sed -i 's/^/PREFIX/' file.txt

The -i flag performs in-place editing. On macOS, you may need -i '' instead:

sed -i '' 's/^/PREFIX/' file.txt

For dynamic prefixes stored in variables:

prefix="[INFO] "
sed "s/^/$prefix/" file.txt

Note the double quotes allow variable expansion.

Using awk

The awk command offers another straightforward solution:

awk '{print "PREFIX" $0}' file.txt

This works well when you need conditional logic:

awk '{print (NR > 1 ? "PREFIX" : "") $0}' file.txt

This prefixes all lines except the first—useful for CSV or tabular data.

Using while loop

For processing stdin or when you need more control:

while IFS= read -r line; do
  echo "PREFIX$line"
done < file.txt

Use IFS= to preserve leading whitespace in each line. This approach is slower than sed or awk but integrates easily into larger bash scripts.

With pipe input

When working with command output:

some_command | sed 's/^/PREFIX/'
some_command | awk '{print "PREFIX" $0}'

Prefixing with timestamps

A practical example—adding timestamps to log lines:

sed "s/^/$(date '+%Y-%m-%d %H:%M:%S') /" logfile.txt

Or dynamically for each line (slower but accurate):

while IFS= read -r line; do
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] $line"
done < logfile.txt

Prefixing multiple files

To process multiple files and save results:

for file in *.txt; do
  sed -i.bak 's/^/PREFIX/' "$file"
done

This creates .bak backups before modification—essential when testing.

Performance comparison

For large files, sed and awk vastly outperform shell loops. Testing with a 100,000-line file:

Use the shell loop only when you need complex conditional logic within the line-processing logic.

Common pitfalls

Escaping special characters: If your prefix contains regex metacharacters like &, \, or /, escape them:

prefix='[ERROR] & '
sed "s/^/${prefix//&/\\&}/" file.txt

Empty lines: All methods handle empty lines correctly—they’ll receive the prefix with no content after it.

File permissions: When using -i, ensure your user has write permissions on the file and its directory.

Practical example: adding log levels

#!/bin/bash

log_file="$1"
level="${2:-INFO}"

case "$level" in
  ERROR)
    sed "s/^/[ERROR] /" "$log_file"
    ;;
  WARN)
    sed "s/^/[WARN] /" "$log_file"
    ;;
  *)
    sed "s/^/[INFO] /" "$log_file"
    ;;
esac

For production use, validate your input and test with shellcheck to catch potential issues.

2026 Best Practices and Advanced Techniques

For Adding a Prefix to Each Line in Bash, understanding both the fundamentals and modern practices ensures you can work efficiently and avoid common pitfalls. This guide extends the core article with practical advice for 2026 workflows.

Troubleshooting and Debugging

When issues arise, a systematic approach saves time. Start by checking logs for error messages or warnings. Test individual components in isolation before integrating them. Use verbose modes and debug flags to gather more information when standard output is not enough to diagnose the problem.

Performance Optimization

Security Considerations

Security should be built into workflows from the start. Use strong authentication methods, encrypt sensitive data in transit, and follow the principle of least privilege for access controls. Regular security audits and penetration testing help maintain system integrity.

These complementary tools expand your capabilities:

Integration with Modern Workflows

Consider automation and containerization for consistency across environments. Infrastructure as code tools enable reproducible deployments. CI/CD pipelines automate testing and deployment, reducing human error and speeding up delivery cycles.

Quick Reference

This extended guide covers the topic beyond the original article scope. For specialized needs, refer to official documentation or community resources. Practice in test environments before production deployment.

← All posts