-e tells sed to execute the next command
line argument as sed program. Since sed programs often contain regular
expressions, they will often contain characters that your shell interprets, so
you should get used to put all sed programs in single quotes so your shell won't
interpret the sed program. In this case, nothing bad would have happened, but
since almost all other examples will contain meta-characters, you really should
get used to quoting your programs. This simple sed program contains a pattern
(``1,10'') and an action (``d''). What sed(1) does is apply all actions whose
pattern match and finally print the line unless the action was ``d''. If you
don't want sed(1) to print each line by default, you can give sed the
-n option. Then only lines that you print explicitly (with the
``p'' action) appear on stdout.
If we wanted to print only the first ten lines, we would have deleted all the lines starting with 11:
$ is the last line. Because sed(1) processes the input
line by line, it does not keep the whole input in memory. This makes sed(1) very
useful for processing large files, but it has it's drawbacks, too. For example,
we can't use
sed -e '$-10,$d',
since sed doesn't know
$ before the end of file, so it doesn't know
$-10 is. This is a major problem, and it
limits sed(1)'s usefulness, but sed(1) still has a large number of appliances.
Another way to get only the first 10 lines is to use the
If we want to delete only one line, the pattern can be
Another possibility is to use the
-e option more than once:
That's why we used the
-e option all the time. In fact, you can
omit it if you have only one command in your program. But you should get used to
-e option, so you won't have to add it if you want to extend
your program later on.
logwhich contains thousands of lines. Now you want to delete all the lines that contain the word ``debug'':
This works just like
grep -v debug.
Note that this spawns two grep processes. The sed equivalent would be:
You might wonder why lines with debug aren't printed if they contain foo. The
answer is that the ``d'' action skips the rest of the patterns and actions, too,
it does not just inhibit the print in the end (which is inhibited here due to
There is a kludge in sed(1) that allows you to set the
from within your sed program if you use ``#n'' as the first
line in your program file. From now on I will assume that you run the examples
The difference between ``i'' and ``a'' is that ``i'' inserts before the current line and ``a'' appends after the current line. So ``1i'' will insert before the first line and ``$a'' will append after the last line.
\tand nonprintable characters are printed as escaped three-digit octal numbers. This example is quite useful as shell alias:
which would just change the string ``foo'' to ``bar''.