5.3. Non-interactive editing

5.3.1. Reading sed commands from a file

Multiple sed commands can be put in a file and executed using the -f option. When creating such a file, make sure that:

5.3.2. Writing output files

Writing output is done using the output redirection operator >. This is an example script used to create very simple HTML files from plain text files.

sandy ~> cat script.sed 1i\ <html>\ <head><title>sed generated html</title></head>\ <body bgcolor="#ffffff">\ <pre> $a\ </pre>\ </body>\ </html> sandy ~> cat txt2html.sh #!/bin/bash # This is a simple script that you can use for converting text into HTML. # First we take out all newline characters, so that the appending only happens # once, then we replace the newlines. echo "converting $1..." SCRIPT="/home/sandy/scripts/script.sed" NAME="$1" TEMPFILE="/var/tmp/sed.$PID.tmp" sed "s/\n/^M/" $1 | sed -f $SCRIPT | sed "s/^M/\n/" > $TEMPFILE mv $TEMPFILE $NAME echo "done." sandy ~> 

$1 holds the first argument to a given command, in this case the name of the file to convert:

sandy ~> cat test line1 line2 line3 

More on positional parameters in Chapter 7.

sandy ~> txt2html.sh test converting test... done. sandy ~> cat test <html> <head><title>sed generated html</title></head> <body bgcolor="#ffffff"> <pre> line1 line2 line3 </pre> </body> </html> sandy ~> 

This is not really how it is done; this example just demonstrates sed capabilities. See Section 6.3 for a more decent solution to this problem, using awk BEGIN and END constructs.

NoteEasy sed

Advanced editors, supporting syntax highlighting, can recognize sed syntax. This can be a great help if you tend to forget backslashes and such.