26. sed 解释器
正如您编写 shell 脚本并通过调用文件名从命令行执行它们一样,您可以设置 sed 脚本以从命令行执行,即 sed 可以作为解释器参与。
为此,请将 #!/bin/sed -f
作为第一行添加到 sedscript.sh
文件中,如下所示。
$ vi myscript.sed
#!/bin/sed -f
# Swap field 1 (employee id) with field 2 (employee name)
s/\([^,]*\),\([^,]*\),\(.*\).*/\2,\1,\3/g
# Enclose the whole line within < and >
s/^.*/<&>/
# Replace Developer with IT Manager
s/Developer/IT Manager/
# Replace Manager with Director
s/Manager/Director/
现在,通过从命令行调用 sed 脚本来直接执行它。
chmod u+x myscript.sed
./myscript.sed employee.txt
您还可以在 sed 脚本的第一行中指定 -n
以抑制输出。
$ vi testscript.sed
#!/bin/sed -nf
/root/ p
/nobody/ p
现在,执行上面的测试脚本,如下所示。
chmod u+x testscript.sed
./testscript.sed /etc/passwd
仅出于测试目的,从 testscript.sed
的第一行中删除 -n
并再次执行它以查看它是如何工作的。
您必须使用-nf
(而不是 -fn
)。 如果指定 -fn
,则执行 sed 脚本时将收到以下错误消息。
$ ./testscript.sed /etc/passwd /bin/sed: couldn't open file n: No such file or directory