Наши партнеры

Книги по Linux (с отзывами читателей)

Библиотека сайта rus-linux.net

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:

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

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
<head><title>sed generated html</title></head>\
<body bgcolor="#ffffff">\

sandy ~> cat txt2html.sh

# 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..."

sed "s/\n/^M/" $1 | sed -f $SCRIPT | sed "s/^M/\n/" > $TEMPFILE

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

More on positional parameters in Chapter 7.

 sandy ~> txt2html.sh test
converting test...

sandy ~> cat test
<head><title>sed generated html</title></head>
<body bgcolor="#ffffff">

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.

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.