Insert 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 insert lines of text. We'll use sed's i command to insert a header at the top of every .js file in a directory.

Instructor: [00:00] Let's say I have a bunch of files that I want to insert a generic header on. In my directory here, you can see I have a lot of JS files. Let's say, my generic header, I want it to be something like copyright with the current year and my name. First, let's figure out how to do it on one file to begin with.

[00:15] I'm going to invoke sed and I'll target the line number, which I want to be the first line. I'll do -i, the i command, which stands for insert, and then a backslash. Then, I'm going to hit enter here to start writing on a new line.

[00:30] Having everything after the -i command come on a new line is only necessary on older versions of sed, such as the one that's on macOS by default. Most Linux distros are going to have a newer version of sed, where you can do this all inline and you don't have to worry about that.

[00:43] Let me put my content here. I'm going to do a comment, "This is copyright 2020," and then I'm going to pass the file I want to modify. Cool, that worked. I outputted the modified file just to stdout here. Let's run this again, and then I'm going to go back up here and do my in-place with no backup, cat it out to double-check it. Looks like that worked.

[01:04] Let's see how we do it on all of my JS files in this directory. Basically, we're going to want to do the same thing, but instead of a single file here, we want to target all JS files. If you're on a newer version of sed, this will work as-is, except you don't need to do the newline, even.

[01:23] On macOS, we've got to write a for loop. Do, for f. I'm going to an ls for all the JS files. Do sed, and then we're going to want to do is in-place with no backup. Then, for our script, I'm going to put the content here, and then I'm going to hit enter again so I get another new line after it, and then close my sed script, pass my file here to sed, and semi-colon. Done.

[01:49] Now let's run that, and then let's cat out file2.js. Looks like that worked. We now just inserted generic text over 11 different files.