Add character to the beginning of each line using sed

The sed command in Linux can be used to do many types of text manipulation. In this tutorial, you’ll learn how to add a character to the beginning of every line using sed. Check out the examples below to see how.

In this tutorial you will learn:

  • How to add a character to the beginning of each line using sed
How to add a character to the beginning of each line using sed
How to add a character to the beginning of each line using sed
Software Requirements and Linux Command Line Conventions
Category Requirements, Conventions or Software Version Used
System Any Linux distro
Software sed
Other Privileged access to your Linux system as root or via the sudo command.
Conventions # – requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command
$ – requires given linux commands to be executed as a regular non-privileged user

Add character to the beginning of each line using sed



Twitter icon Follow LinuxConfig.org on Twitter for the latest tips and tricks about Linux!

The sed command can be used to add any character of your choosing to the beginning of each line. This is the same whether you are adding a character to each line of a text file or standard input.

Check out the examples below to see how to add a character to the begging of each line using sed. Note that we are using the Bash shell (the default shell on nearly all Linux systems) for these examples.

Various examples of adding a character to every line using sed in Linux
Various examples of adding a character to every line using sed in Linux
  1. Let’s start by adding a # character (pound sign) to the beginning of each line by using the following sed command. We’ll run the command on a file simply named file.txt.
    $ sed 's/^/#/' file.txt
    

    The ^ character is what instructs the sed command to add a character to the beginning of each line.

  2. Here’s the syntax for adding a space to the beginning of each line using sed.
    $ sed 's/^/ /' file.txt
    
  3. We can also redirect the output produced by the sed command and save it to a new file:
    $ sed 's/^/#/' file.txt  > new-file.txt
    


  4. Alternatively, use the -i option with the sed command to edit a file in place. Be careful, as this will overwrite the file with the new changes.
    $ sed -i 's/^/#/' file.txt
    

Closing Thoughts

In this tutorial, we saw how to add a character to the beginning of each line using the sed command in Linux. The sed command is one of the most efficient ways to manipulate large amounts of text. You can use the examples from this tutorial to add any character (or multiple characters) to every line.