Linux Command to Add a Prefix to Each Line

Adding a Prefix to Each Line in Linux

Here are common methods to add a prefix to every line of a file:

1. Using sed

Replace PREFIX with your desired string:

sed 's/^/PREFIX/' input.txt
Example:
sed 's/^/Hello /' file.txt

This turns:

World
Linux

into:

Hello World
Hello Linux

2. Using awk

Basic usage:

awk '{print "PREFIX"$0}' input.txt
Example:
awk '{print "https://"$0}' domains.txt

Output:

https://example.com
https://linux.org

3. In-Place File Modification

Add -i to sed or perl to edit files directly:

sed -i 's/^/PREFIX/' input.txt
perl -i -pe 's/^/PREFIX/' input.txt

4. Handling Special Characters

If the prefix includes slashes, change the sed delimiter:

sed 's|^|/usr/local/|' paths.txt

For quotes or spaces in awk, escape them properly:

awk '{print "\"Quote: \""$0}' text.txt

5. Adding Prefix While Using Pipelines

cat input.txt | sed 's/^/PREFIX/'

Or with awk:

grep "pattern" input.txt | awk '{print "PREFIX"$0}'

Summary

  • Use sed or awk to easily prefix lines.
  • Adjust delimiters when handling special characters.
  • Use -i for in-place modifications.

Comments

Popular Posts

Puppet Code Deploy Troubleshooting & Resolution Guide

Fix: SSH Permission Denied Issue | Real Solution

Linux Process Termination Signals Explained with Examples