How to Use sed to Insert Character at Beginning of Lines in File


Often you may want to use sed to insert a specific character at the beginning of one or more lines in a file.

You can use the following methods to do so:

Method 1: Insert Character at Beginning of Each Line in File

sed 's/^/_/' employees.txt

This particular example inserts an underscore ( _ ) at the beginning of each line in the file named employees.txt.

Method 2: Insert Character at Beginning of Specific Line Number in File

sed '3 s/^/_/' employees.txt 

This particular example inserts an underscore only at the beginning of line number 3 in the file named employees.txt.

Method 3: Insert Character at Beginning of Specific Range of Line Numbers in File

sed '3,5 s/^/_/' employees.txt 

This particular example inserts an underscore at the beginning of each line in the line number range of 3 to 5 in the file named employees.txt.

The following examples show how to use each method in practice with the following file named employees.txt that contains the ID numbers for various employees at some company:

Example 1: Insert Character at Beginning of Each Line in File

We can use the following syntax to insert an underscore at the beginning of each line in the file named employees.txt:

sed 's/^/_/' employees.txt

The following screenshot shows how to use this syntax in practice:

sed insert character at beginning of each line in file

Notice that an underscore has been inserted at the beginning of each line in the file.

Example 2: Insert Character at Beginning of Specific Line Number in File

We can use the following syntax to insert an underscore only at the beginning of line number 3 in the file named employees.txt:

sed '3 s/^/_/' employees.txt

The following screenshot shows how to use this syntax in practice:

sed insert character at beginning of line at specific line number

Notice that an underscore has only been inserted at the beginning of line number 3 in the file.

Example 3: Insert Character at Beginning of Specific Range of Line Numbers in File

We can use the following syntax to insert an underscore only at the beginning of line numbers 3 through 5 in the file named employees.txt:

sed '3,5 s/^/_/' employees.txt

The following screenshot shows how to use this syntax in practice:

sed insert character at beginning of line for specific line number range

Notice that an underscore has only been inserted at the beginning of line numbers 3 through 5 in the file.

Related Tutorials

The following tutorials explain how to perform other common tasks in sed:

How to Use sed to Insert a Line After Match
How to Use sed to Insert Line at Specific Line Number
How to Use sed to Delete Specific Line Numbers from File
How to Use sed to Extract All Lines Containing a Pattern

Leave a Reply