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.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!