image_pdfimage_print

Non-interactive editing with SED

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:

  • No trailing white spaces exist at the end of lines.
  • No quotes are used.
  • When entering text to add or replace, all except the last line end in a backslash.

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 here.

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 this for a more decent solution to this problem, using awk BEGIN and END constructs.

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

Source: Non-interactive editing with SED