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
|Category||Requirements, Conventions or Software Version Used|
|System||Any Linux distro|
|Other||Privileged access to your Linux system as root or via the
# – requires given linux commands to be executed with root privileges either directly as a root user or by use of
$ – requires given linux commands to be executed as a regular non-privileged user
Add character to the beginning of each line using sed
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.
- Let’s start by adding a
#character (pound sign) to the beginning of each line by using the following
sedcommand. We’ll run the command on a file simply named
$ sed 's/^/#/' file.txt
^character is what instructs the
sedcommand to add a character to the beginning of each line.
- Here’s the syntax for adding a space to the beginning of each line using
$ sed 's/^/ /' file.txt
- We can also redirect the output produced by the
sedcommand and save it to a new file:
$ sed 's/^/#/' file.txt > new-file.txt
- Alternatively, use the
-ioption with the
sedcommand to edit a file in place. Be careful, as this will overwrite the file with the new changes.
$ sed -i 's/^/#/' file.txt
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.