box.matto.nl
Enjoying Open Source Software

# Scripting with ed and here documents

Ed is the standard editor and although it is very old it is still a very useful and powerful editor.

Ed is made to be used interactively, but we can also use it in scripts. The use of here documents is one way to do this.

A simple example:

ed -s myfile << EOF
a
A new line
.
w
EOF


## Remove from the first line to line with some pattern

A handy way of removing the lines from the start of a text file to some arbitrary line containing a certain pattern, is to use line labels. In Ed, we can label a line with the k' command, like this:

kx


This gives the line the label x'', which we address with 'x (apostrophe, immediately followed by the label name).

So, if we want to remove the preamble of a Latex document this would do the trick:

ed -s mylatexfile << EOF
H
/\\\begin{document}/
kx
1,'xd
w
EOF


The first line toggles the explanation flag (H').

The second line searches for \begin{document}. We have to escape the backslash with extra backslashes, because of the shell we run this script from.

The line kx' is used to label the line with the \begin{document} pattern.

The line 1,'xd' deletes all the lines from the first to the line with the \begin{document} pattern.

The last line w' is to write the buffer back to disk.

## Replace from the first line to line with some pattern with other text

If we want to replace the deleted preamble with a different one, we can no give the command 1i', meaning "go to line 1 and insert before that":

ed -s mylatexfile << EOF
H
/\\\begin{document}/
kx
1,'xd
1i
\documentclass [english,useplainpaper]{article}
....
w
EOF


The text to insert can be arbitrary long, it does not have to be the same number of lines as the number of deleted lines.

## Direct addressing the line with the search pattern

A shorter way to remove from the first line to a line with some pattern is to direct it directly, like this:

ed -s mylatexfile << EOF
H
1,/\\\begin{document}/d
w
EOF


Sometimes, using the first method, with adding a label to the specific line, it is easier to understand.

## Learn Ed and prosper

Of course, this are some silly examples, Ed can do so much more :)

If you have not done yet, learn yourself some basic Ed and practice until you get comfortable with it, and than start to write some scripts with here-documents. The time you invest on this is well worth it, you'll acquire a skill that can be extremely useful in the future.

Tags: