Skip to navigation

Sed example 1

Many things are easiest to learn by looking at examples. I find this to be especially true for sed. Sed stands for “stream editor”, and it is very handy to perform bulk editing of text files. To get started, I refer you to this very nice tutorial. I’m planning to archive some of the small editing tasks I did with sed on this blog, both for my own reference and in case anyone wants to look at sed examples. These examples worked when I used them to edit the files I wanted to edit — but of course no guarantee that there isn’t a glitch. Always make a backup.

So here’s the first example. I have a file containing assignments done by students, 100 of them, all one after another in a single text file. I’ve graded them and want to e-mail them back. I’ll use sed and mutt to do this conveniently from the commandline.

The text file looks like this:,Firstname Lastname,
The above line is followed by the student's answer to the assignment,
bla bla bla,
several lines of text. At the end, the grade is out of five points:
> 2/5.,Firstname2 Lastname2,
The first assignment is followed by the next assignment, which again ends in
a grade, and so on for 100 students.
> 4/5.

First, I want to get rid of the student name and the two commas on the line with the e-mail address, so that the e-mail address is on a line by itself. The sed command:


More specifically, this looks for a regexp matching the pattern of an ampersand followed by any sort of stuff ( “.*” ), a comma, again anything, followed by another comma, and replaces it by reinserting the first found pattern that we’ve specified with the two escaped brackets “\(” and “\)”.
Next, I turn each line with an e-mail address into a mutt command to send anything up to the next “EOF” to that e-mail address, with a sensible subject line. The sed command:

s|\(.*@.*\)|mutt \1 -s "psych 153 a3" << EOF|

We insert two newlines and “EOF” after each grade. The grade is identified as a pattern of “/5.”, and the period needs to be escaped (otherwise, it would be a regexp match for any character):


You can put all the above statemens into a file, maybe call it “sedfile”, backup your work and then run it with “in place” replacement, i.e., the original file gets overwritten:

cp ass3 ass3.bkp
sed -i -f sedfile ass3

Finally, make the file executable and run it:

chmod 700 ass3

One Response to “Sed example 1”

  1. Stanislows from Nanty Glo PA. Says:

    Dr. Promberger, Ph.D

    Congratulations on your doctorate degree, and thanks for providing the sed example. May you have the best of success!