How to Use sed to Delete All Lines Starting with Specific Pattern


Often you may want to use sed to delete all lines from a file that start with a specific pattern.

You can use the following basic syntax to do so:

sed -i '/^##/d' cities.txt

This particular example deletes all lines that start with the pattern ## in the file named teams.txt.

Note that we use the -i flag in sed to delete the lines in-place.

If you’d like to store the results to a new file then you can use the following syntax:

sed '/^##/d' cities.txt > cities_new.txt

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

Note: The ^ operator is used to find the start of a string. 

Example: Use sed to Delete All Lines Starting with Specific Pattern

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

Suppose that we would like to delete all lines from the file that start with the pattern ##.

We can use the following syntax to do so:

sed -i '/^##/d' cities.txt

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

sed delete lines starting with

Notice that when we use the cat command again to view the contents of the file that all lines starting with ## have been removed from the file.

Note that we could also use the following syntax to instead remove all lines starting with ## and save the results to a new file:

sed '/^##/d' cities.txt > cities_new.txt

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

sed delete lines starting with pattern and save to new file

Notice that when we use the cat command to view the contents of the file named cities_new.txt that it contains all lines from the original file with the lines starting with ## removed.

Related Tutorials

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

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