Delete Lines of Text with sed in Bash

Cameron Nokes
InstructorCameron Nokes
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 4 years ago

In this lesson, you'll learn how sed can be used to delete lines of text. You can use a regex or line numbers to target a line for deletion. This makes a sed a powerful tool for automatically performing lots of tedious text deletions for you.

Instructor: [00:00] In my directory here, I have one file, this cloneelement.js, which I got from the React repository. Let's glance at this file. You see it has a lot of whitespace in it. Let's say that I want to delete all lines that contain empty lines. Let's see how we do that here with sed.

[00:16] My script will go here, and then I'll pass the file name. Right here, this is the address of the command. This would be a regex that I'm going to leave empty for now, and then, I'm going to use the d command, which stands for delete.

[00:30] Let's fill in our regex here. To get all empty lines, we're going to do the start operator and then the end-of-line operator, like that, and then d will delete it. Let's run that and see what happens.

[00:42] You see, it's condensed it a lot. If we want to modify the file, instead of outputting the modifications to stdout, we can use the in-place flag, but no backups. If we run that and then check out our file, we can see that we modified the file in-place. Cool, that worked.

[01:01] We can also delete line numbers. Let's get the first two lines of cloneElement. If we wanted to delete that first line with the [inaudible] sign, we could pass 1 as the line number and then the d command. You can see now that empty array thing is the first line.

[01:18] Another handy one is deleting the last line. To do that, we use the special $ symbol, which sed interprets as the last line of the file. You can see that worked, because we're missing the closing curly brace that was the last line.