How to Use sed to Insert Empty Line in a File


Often you may want to use sed to insert an empty line in a specific location of a file.

You can use the following basic syntax to do so:

sed '/Houston/G' cities.txt

This particular example inserts a new line into the file named cities.txt after the line which contains the pattern “Houston.”

Note that the G command in sed is specifically designed to append a newline to a file after matching a particular pattern.

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

Example: Use sed to Insert Empty Line in a File

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

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

Suppose that we would like to insert an empty line into the file directory after the line that contains the pattern “Houston.”

We can use the following syntax to do so:

sed '/Houston/G' cities.txt

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

sed insert empty line in file

Notice that an empty line has been inserted into the file directly after the line that contains “Houston.”

Note that you can also use the -i flag if you would like to modify the file in-place:

sed -i '/Houston/G' cities.txt

This syntax would allow you to insert the empty line into the file in-place.

Related Tutorials

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

How to Use sed to Delete All Lines Containing Specific String
How to Use sed to Replace All Occurrences of Pattern
How to Use sed to Replace All Text After Match
How to Use sed to Extract All Lines Containing a Pattern

Leave a Reply