ITEEDU

5.3. 非交互编辑

5.3.1. 从文件读取sed命令

多个 sed 命令可以一起放到一个文件中,用 -f 选项来执行。当建立了一个这样的文件,请确保:

  • 每行的末尾没有多余的空格。

  • 不能使用引用。

  • 当进入文本来添加和替换的时候,除了最后行已为的所有行都要以反斜扛结尾。

5.3.2. 写输出文件

当使用重定向符号 >的时候,写输出就完成了。这是一个例子脚本,用来从纯文本文件建立非常简单的HTML文件。

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 把第一个参数送到命令中,这个例子中它是要转换的文件的名字:

sandy ~> cat test
line1
line2
line3

更多的位置参数请参见 第 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 ~>

这并不是真的是这么完成的;这个例子仅仅证明了 sed 的实际能力。参见 第 6.3 节 “Gawk变量” 得到一个对这个问题来说更好的解决方法,使用 awk BEGINEND 结构。

[注意] 便捷的sed

高级编辑器,支持语法的高亮来识别 sed 语法。如果你忘记反斜杠之类的它将提供很大的帮助。