How to Use sed to Remove a Substring (With Example)


Often you may want to use sed to remove a specific substring from a string.

You can use the following basic syntax to do so:

sed 's/West//' team_names.txt

This particular example will remove the substring “West” from each line in the file named team_names.txt.

Note that we use the sed s command to “substitute” one pattern for another.

In this particular example we specify that the pattern “West” should be substituted with nothing, which effectively removes this substring from each line.

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

Example: How to Use sed to Remove Substring

Suppose that we have a text file named team_names.txt that contains the names of various basketball teams.

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

Suppose that we would like to remove the substring “West” from each line in the file.

We can use the following syntax to do so:

sed 's/West//' team_names.txt

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

sed remove substring

Notice that the substring “West” has been removed from each line in the file.

Note that you could also use the > command to save these changes to a new file:

sed 's/West//' team_names.txt > team_names_new.txt

This particular syntax would remove the substring “West” from each line in the file named team_names.txt and then save these changes to a new file named team_names_new.txt.

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 Delete All Empty Lines in File
How to Use sed to Delete Specific Line Numbers from File

Leave a Reply