How to Use sed to Insert Character at Specific Position


Often you may want to use sed to insert a character at a specific position in a string.

You can use the following basic syntax to do so:

sed 's/./&-/4' employees.txt

This particular example inserts a a dash after the character in position 4 of each line in the file named employees.txt.

Here is how this syntax works:

  • We use the s command to perform a “substitution”
  • We use the 4 to specify that only the character in position 4 of the string should be substituted
  • We use a period ( . ) to specify that any character in position 4 should be replaced.
  • We use &- to specify that the replacement should be the existing character in position 4 ( & ) along with a dash.

The following example shows how to use this syntax in practice.

Example: Use sed to Insert Character at Specific Position

Suppose we have a file named employees.txt that contains the ID numbers for various employees at some company.

We can use the cat command to view the contents of this file:

We can use the following syntax to insert a dash after the character in position 4 of each line in the file:

sed 's/./&-/4' employees.txt

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

sed insert character at position

Notice that a dash has been inserted after the character in position 4 of each line in the file.

Feel free to replace the dash with any character that would like.

Also note that you can use the > command to save these changes to a new file:

sed 's/./&-/4' employees.txt > employees_new.txt

This particular example will insert a dash after the character in position 4 of each line in the file named employees.txt and save the results to a new file named employees_new.txt.

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