How to Insert a String to the Beginning of a File on Linux

bash arguments, pass parameter, pass argument to script

Sometimes, you need to add a line of text to the start of a file on Linux—maybe for logging, configuration, or just for organization. While you could open the file and manually paste the text, that’s not exactly efficient, especially if you’re dealing with multiple files. Luckily, Linux gives you a few quick ways to do this directly from the terminal.

Here is a preview of the article:

  • For quick edits, sed is your best bet.
  • If you want a simple approach, echo + cat works great.
  • For system-wide compatibility, ed is a reliable choice.
  • When working with structured data, awk provides more flexibility.

Best Ways to Insert a String at the Beginning of a File

Use sed to Add a String to the Start of a File

One of the fastest ways to prepend text to a file is by using sed. This tool allows you to modify text without opening the file in an editor.

sed -i '1s/^/[INFO] Log Entry - $(date)
/' filename

How This Works:

  • 1s/^/[INFO] Log Entry - $(date) / inserts a timestamped log entry at the start of the file.
  • The -i flag ensures the changes are made directly to the file.
  • The \n ensures that the new string appears on a new line.
See also  Ultimate Guide to Installing Linux on Your Chromebook

If you don’t want to overwrite the original file, remove the -i flag and redirect the output:

sed '1s/^/[INFO] Log Entry - $(date)
/' filename > newfile

Example Output: Before:

Existing content line 1
Existing content line 2

After:

[INFO] Log Entry - Mon Feb 5 12:00:00 UTC 2025
Existing content line 1
Existing content line 2

Use Case: Ideal for adding timestamped log entries in system logs or data files.


Use echo and cat to Prepend Text

If you prefer a more straightforward approach, combining echo and cat can do the trick:

echo "[WARNING] System reboot scheduled at $(date)" | cat - filename > temp && mv temp filename

Why This Works:

  • echo outputs a new warning message with a timestamp.
  • cat - filename merges the new string with the existing file.
  • The output is stored in temp, which then replaces the original file.

Example Output: Before:

System running normally

After:

[WARNING] System reboot scheduled at Mon Feb 5 12:00:00 UTC 2025
System running normally

Use Case: Useful for adding system status messages before the original content.


Use ed to Modify the File Directly

Another option is ed, one of the oldest text editors available on Unix systems. Here’s how to use it:

ed -s filename <<EOF
0a
[NOTICE] File modified on $(date)
.
w
EOF

Breaking It Down:

  • 0a tells ed to insert text before the first line.
  • . signals the end of the new input.
  • w writes the changes back to the file.

Use Case: A lightweight alternative for modifying system configuration files.


Use awk for Prepending Text

If you’re working with structured data, awk can be an efficient way to add a string at the beginning of a file:

awk 'BEGIN {print "Timestamp: " strftime("%Y-%m-%d %H:%M:%S")} {print}' filename > temp && mv temp filename

Why Use awk?

  • The BEGIN block ensures the new string is printed before the existing content.
  • It reads and prints the rest of the file line by line.
  • The output is saved to temp, then moved back to overwrite the original file.
See also  How to disable 'Last Login' welcome message in Linux

Example Output: Before:

Data entry 1
Data entry 2

After:

Timestamp: 2025-02-05 12:00:00
Data entry 1
Data entry 2

Use Case: Best suited for data logs where structured timestamps are required.

Considerations for Large Files

If your file is very large, avoid unnecessary duplication to improve performance:

  • sed -i and ed are best for modifying files in place.
  • echo | cat and awk create temporary files, which may not be ideal for very large datasets.
  • For massive log files, consider using head -n to verify changes before applying them.

Frequently Asked Questions

Will these commands work on all Linux distributions?

Yes! sed, awk, echo, cat, and ed are available on almost every Linux system, so you shouldn’t run into compatibility issues.

Can I insert multiple lines at the beginning of a file?

Yes! You can use \n within sed, or modify ed to insert multiple lines before saving the file.

What if I accidentally overwrite my file?

It’s always a good idea to make a backup. Before making any changes, run cp filename filename.bak so you have a safe copy.

Is there a way to do this without creating a temporary file?

Yes! sed and ed modify the file directly. Methods using awk or cat often require a temporary file.

Can I use these methods for binary files?

It’s not recommended. These tools work best with text files, and modifying binary files could corrupt them.

Photo of author
As Editor in Chief of HeatWare.net, Sood draws on over 20 years in Software Engineering to offer helpful tutorials and tips for MySQL, PostgreSQL, PHP, and everyday OS issues. Backed by hands-on work and real code examples, Sood breaks down Windows, macOS, and Linux so both beginners and power-users can learn valuable insights. For questions or feedback, he can be reached at sood@heatware.net.