sed script files

Isolating the lines was only the first step! We still have to uncomment the lines and then save the result as a template. Although we can write this as one single sed command string, we can already see that it will be awkwardly long and difficult to read and edit. Thankfully, the sed command does have the option to read its commands from an input file, often known as a script. We use the -f option with sed to specify the file we want to read as our control.

We have already seen that we can isolate the correct lines from the file. So, the first line of the script configures the lines that we will work with. We implement the brace brackets {} to define a code block immediately after the selected lines.
A code block is one or more commands that we want to run on a given selection.

In our case, the first command will be to remove the comment and the second command will be to write the pattern space to a new file. The sed script should look like the following example:

/^#<VirtualHost/,/^#<\/VirtualHost/ { 
s/^#// 
w template.txt 
} 

We can save this file as $HOME/vh.sed.

In the first line, we select the lines to work with, as we have previously seen, and then open the code block with the left brace. In line 2, we use the substitute command, s. This looks for lines that start with a comment or #. We replace the comment with an empty string. There are no characters or spaces between the middle and end forward slash. In English, we are uncommenting the line but, to the code, this is replacing the # with an empty string. The final line of code uses the write command, w, to save this to template.txt. To help you see this, we have included the following screenshot of the vh.sed file:

We can see all of our efforts come to fruition now by ensuring that we are in the same directory as the httpd.conf and vh.sed files that are executing the following command:

$ sed -nf vh.sed httpd.conf  

We have now created the template.txt file within our working directory. This is the isolated uncommented text from the httpd.conf file. In simple terms, we have extracted the seven correct lines from over 350 lines of text in milliseconds, removed the comment, and saved the result as a new file. The template.txt file is displayed in the following screenshot:

Now we have a template file that we can begin to work with to create virtual host definitions. Even though it's Apache that we have been looking at, the same idea of uncommenting the text or removing the first character of selected lines can apply to many situations, so take this as an idea of what sed can do.