Join David D. Levine for an in-depth discussion in this video Using the most important sed command, part of SED Essential Training.
- View Offline
- The most important sed command is sed s slash old slash new, file. This replaces the first occurrence of the word "old" on each line of the file with the word "new." In this example, "sed" invokes the sed program, "s" specifies sed's s command, for substitute, slash is to limit the command from its two arguments, the word "old" represents the text that is searched for, and the word "new" represents the text that replaces it. Note that the whole s command is enclosed in single quotes.
I'll explain more about that later. Here's an example of sed's s command in action. We'll start with our dukeofyork.txt example file. So the sed command is sed s slash lowercase "the" to all-caps "the" dukeofyork.txt. Again, note that the entire s command, including its arguments, is enclosed in single quotes. Note that sed is always case-sensitive, so in this case we've replaced lowercase "the" with the all-caps "the," but it did not catch the initial-cap "the" at the beginning of the first line of the file.
Note that it has replaced the first lowercase "the" with all-caps "the" on each line. It does not, for example, change "the" in "the hill" on line three to all caps. It's important to note that sed does not actually edit its input file. I'll cat the dukeofyork.txt file and you'll see that the original file has not been changed by the substitution performed on the previous line. If you do want to modify the file, you can take that sed command and redirect the output into another file.
For example, new.txt, so now if I cat new.txt, you'll see that the modified output was saved in that file. The replacement text in this case is three letters, the same as the original text, but this does not have to be the case. The replacement text can be shorter. For example, we can change "marched" to "ran." Or the replacement text can be larger than the original. We can replace "men" with "women." The replacement text can even be empty.
We can replace "them" with nothing. So you see here, it's removed the word "them" but you can see that there are still two spaces where it had been.
- Understanding input, output, files, and pipes
- Modifying the "s" command
- Using character classes and quantifiers
- Controlling printing
- Reading and writing files
- Appending, inserting, and editing entire lines
- Writing programs in SED
- Using advanced programming commands