How to Use sed to Insert a Tab (With Examples)


Often you may want to use sed to insert a tab character into one or more lines of a file.

You can use \t placed inside of the syntax $’ ‘ to do so.

The following examples show how to use this syntax to insert tabs into the following file named employees.txt that contains the ID values for various employees at some company:

Example 1: Use sed to Insert Tab in First Line of File

Suppose that we would like to insert a line into the first line of the file that contains the following text:

  • EMP    ID

To ensure that a tab is inserted between EMP and ID, we can use the following syntax:

sed $'1iEMP\tIDS' employees.txt

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

sed insert tab into header row

Notice that the exact text that we specified with a tab has been inserted into the first line of the file.

Note: We used 1i to insert a new line into the first row of the file.

Example 2: Use sed to Insert Tab in Each Line of File

Suppose that we would like to insert the string ID: followed by a tab at the beginning of each line in the file.

We can use the following syntax to do so:

sed $'s/^/ID:\t/' employees.txt

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

sed insert tab at beginning of each line in file

Notice that the string ID: followed by a tab has been inserted into the beginning of each line 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