How to Use sed to Insert Line with Leading Spaces


Often you may want to use sed to insert a line with leading spaces into a file in a specific location.

You can use the following basic syntax to do so:

sed -i "4i \    Miami" cities.txt

This particular example will insert a line into row number 4 of the file named cities.txt with the following text:

  • ”    Miami”

Notice that this text has four leading spaces.

Here is what the various commands do:

  • -i: Specifies that the file should be modified in-place
  • 4i: Specifies that we want to insert a new line at row number 4
  • \: Used to escape the leading spaces

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

Example: Use sed to Insert Line with Leading Spaces

Suppose we have a file named cities.txt that contains the names of various U.S. cities:

Suppose that we would like to delete insert a line into row number 4 of the file with the following text:

  • ”    Miami”

Suppose we attempt to use the following syntax to do so:

sed -i "4i    Miami" cities.txt

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

Notice that when we use the cat command to view the contents of the file that the new line has been inserted into row number 4 but it does not contain leading spaces.

This is because we failed to use a backslash ( \ )to escape the spaces.

We must use the following syntax instead:

sed -i "4i \    Miami" cities.txt

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

sed insert line with leading spaces

Notice that when we use the cat command again to view the contents of the file that a new line has been inserted into row number 4 with four leading spaces, just as we specified.

Related Tutorials

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

How to Use sed to Print Out Line Numbers
How to Use sed to Print Specific Lines in File
How to Use sed to Print Every nth Line of File
How to Use sed to Extract All Lines Containing a Pattern

Leave a Reply