Unix's File Editor: sed



next up previous contents index
Next: General Text Selection: Up: Unix Toolkit Previous: Compare Files: diff

Unix's File Editor: sed

The editors Emacs and vi are used to make changes in files interactively. Yet sometimes you want to make particular changes in many files or repeat the same editing again in the future, or to do editing from the command line of Unix and pipe the results to yet other commands. For these purposes, which are not as esoteric as they may appear at first, sed is indispensable. For example, suppose your files contain data of the form 1.12D+33, but your graphics program doesn't like the D for an exponent. Or suppose you want to convert your paper from nroff to LaTeX. Or perhaps you want to delete all lines containing the string copyright (c) by IBM from a group of files.gif These operations of substitution and deletion make sed a must to learn (you'll have time in your jail cell).      

The sed command, like awk, which we describe next, are used as a programming language to create sed scripts. These scripts are useful for complicated or repetitive debugging chores. Quite often, sed is used on the command line with simple options. These options are of some historical interest since they are based on ed, the old Unix line editor now mercifully extinct and forgotten. When used from the command line, only a subset of the full sed options is needed.


sed OPTIONS
-e s/pat1/pat2/
Substitute pat2 for one pat1 per line.
-e s/pat1/pat2/g
Substitute pat2 for every pat1 per line.
-e /pat1/d
Delete lines with pat1.
-e y/str1/str2/
Substitute characters in str2 for those in str1.

In our first example we start with the data file graph.dat containing x-y pairs:


4.05D-09 11.35D+03 File graph.dat 9.73D-09 9.89D+03 10.8D-09 9.63D+03

We must change the D to an e for our graphics program. Rather than do this by hand with an editor, we use sed, which is quicker and gives us a tool to edit future files:

% sed -e "s/D/e/g" graph.dat | xplot   	Edit and pass directly to xplot.   

Notice that, if we had not added the g option for global changes, only the first D per line would have been changed:

% sed -e "s/D/e/" graph.dat   	Leave off the g and use standard output.   
4.05e-09  11.35D+03   	   
9.73e-09  9.89D+03   	   
10.8e-09  9.63D+03   	   

In the next example we first delete all comments from a Fortran file, that is, all lines starting with a c or C, and then use the y option to translate all uppercase letters into lowercase (the same function as tr provides):

% sed -e "/^[c,C]/d" prog.f >prog2.f   	 Strip comments and put into prog2.f.   
% sed -e "y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/" prog.f > prog2.f   	   



next up previous contents index
Next: General Text Selection: Up: Unix Toolkit Previous: Compare Files: diff