SlideShare a Scribd company logo
1 of 19
Sed 命令详解
1.sed -n '2'p filename
打             印                 文               件             的                  第                 二               行                   。
2.sed -n '1,3'p filename
打             印                 文               件             的                    1               到                   3               行
3. sed -n '/Neave/'p filename
打        印            匹         配               Neave            的           行             (       模           糊               匹           配       )
4. sed -n '4,/The/'p filename
在               第                   4                行               查                  询                  模                   式               The
5. sed -n '1,$'p filename
打       印         整         个           文        件       ,         $         表          示          最       后               一       行       。
6. sed -n '/.*ing/'p filename
匹   配       任     意       字     母       ,       并    以       ing       结       尾       的       单   词       (       点       号       不   能       少   )
7 sed -n / -e '/music/'= filename
打印匹配行的行号,-e 会打印文件的内容,同时在匹配行的前面标志行号。-n 只打印出实际的行号。
8.sed -n -e '/music/'p -e '/music/'= filename
打    印        匹         配       的       行       和        行    号          ,       行         号       在       内       容           的       下       面
9.sed '/company/' a "Then suddenly it happend" filename
选择含有 company 的行,将后面的内容"Then suddenly it happend"加入下一行。注意:它并不改变
文 件 , 所 有 操 作 在 缓 冲 区 , 如 果 要 保 存 输 出 , 重 定 向 到 一 个 文 件 。
10. sed '/company/' i "Then suddenly it happend" filename
同        9          ,           只           是            在       匹             配           的           行           前               插       入
11.sed '/company/' c "Then suddenly it happend" filename
用   "Then suddenly it happend"                       替       换       匹       配         company         的           行       的       内   容       。
12.sed '1'd ( '1,3'd '$'d '/Neave/'d) filename
删   除       第     一       行     (1      到        3   行       ,     最       后       一       行       ,   匹       配           Neave       的       行   )
13.[ address [                  ,                address]] s/ pattern-to-find /replacement-pattern/[g p w n]
s 选项通知 s e d 这是一个替换操作,并查询 pattern-to-find,成功后用 replacement-pattern 替换它。


替                   换                   选                    项                     如                       下                       :
g缺省情况下只替换第一次出现模 式, 使用 g 选 项替 换全 局所 有出 现模 式。
p 缺省 s e d 将所有被替换行写入标准输出,加 p 选项将使- n 选项无效。- n 选项不打印输出结果。
w 文件名使用此选项将输出定向到一个文件。 (注意只将匹配替换的行写入文件,而不是整个内容 )
14.sed s'/nurse/"hello "&/' filename
将            'hello '           增                加           到               'nurse' 的                 前                   面           。
15. sed '/company/r append.txt' filename
在 匹 配 company 的 行 的 下 一 行 开 始 加 入 文 件                                                                  append.txt 的 内 容 。
16. sed '/company/'q filename
首        次            匹         配               company                后           就           退           出               sed         程           序


只   所    以        看       sed       命       令    ,   是       因     为       我     遇      到      了       这       个   一           个   问       题   。
网上有很多教程,他们发表了很多程序代码,但是作者为了解释方便,都对程序作了行号编码,就像下面
这                                               样                                                  :
代                                                                   码                                                                     ::


1:#!/bin/bash
2:#rename file extesions
3:#
4:#       rfe old_extensions new_extension




假 设 这 个 文 件 名 是 tmp , 那 么 我 们 可 以 使 用 下 面 的 命 令 来 去 掉 这 个 行 号 和 冒 号 ( : )


代                                                                   码                                                                     ::




sed -e s'/^[0-9]{1,}://g' tmp




不过上面的命令的命令有一个缺点,那就是如果这个行号不是数字开头,而是有空格的话,那就需要修改
匹配规则,规则应该修改为匹配第一个非空白字符是数字开始,后面接一个冒号的配对。命令如下:


代                                                                   码                                                                     ::


sed -e s'/^[^0-9a-zA-Z]*[0-9]{1,}://g' tmp




这令我很兴奋,于是想看看 sed 到底有多厉害,看了以后,明白的是不是 sed 有多厉害,就像 awk 一样,
他     们           只           是       把       正         规       表           达       式        用          到       了       极         致       。


以                     Redhat6.0 为                           测                   试                   环                   境
事 实 上 在               solaris         下 的     sed       命 令 要 比                 linux    强 , 但 因 为 没 有 测 试
环     境       ,       我       这       里   只       给     在       linux       下       经       过       测       试   的       用     法       。
★命                    令                   行                     参                数                      简               介
★首        先       假           设       我   们         有       这       样       一       个       文       本       文       件       sedtest.txt
★输                    出               指               定                 范               围               的               行                 p
★在            每           一       行       前           面         增           加       一           个       制           表       符         (^I)
★在                每                   一             行               后               面               增               加               --end
★显         示          指           定       模         式           匹       配        行          的       行           号       [/pattern/]=
★在        匹       配           行       后   面         增       加       文       本        [/pattern/]a 或                者       [address]a
★删            除           匹           配         行           [/pattern/]d 或                  者           [address1][,address2]d
★替            换           匹           配       行             [/pattern/]c 或                 者           [address1][,address2]c
★在        匹       配           行       前   面         插       入       文       本         [/pattern/]i 或               者       [address]i
★替        换       匹       配   串       (   注     意       不       再   是       匹    配      行       ) [addr1][,addr2]s/old/new/g
★限                定               范         围               后           的            模              式           匹               配
★指        定           替       换       每       一         行       中       匹       配        的          第       几       次       出       现
★&                  代                     表                      最                    后                匹                   配
★利           用              sed               修             改             PATH                环            境           变               量
★测          试           并           提           高               sed           命           令        运           行           效           率
★指            定              输              出               文                件            [address1][,address2]w outputfile
★指                定                   输                     入                 文                件                   [address]r inputfile
★替            换              相                应               字               符               [address1][,address2]y/old/new/
★!                          号                               的                             使                            用
★ c            正               则                 表               达               式               c的               使               用
★ sed         命          令          中           正           则            表        达           式        的           复       杂            性
★转       换           man            手         册           成           普       通       文           本        格           式       (        新      )
★ sed       的         man           手         册         (        用        的       就       是        上           面       的       方        法      )
★命                   令                    行                       参                   数                    简               介


sed
-e script 指                  定                    sed                     编               辑                    命               令
-f scriptfile 指          定          的           文           件         中           是       sed          编           辑       命            令
-n 寂 静 模 式 , 抑 制 来 自 sed 命 令 执 行 过 程 中 的 冗 余 输 出 信 息 , 比 如 只
显         示              那              些                 被               改           变                的           行                。
不 明 白 ? 不 要 紧 , 把 这 些 肮 脏 丢 到 一 边 , 跟 我 往 下 走 , 不 过 下 面 的 介 绍 里
不 包 括 正 则 表 达 式 的 解 释 , 如 果 你 不 明 白 , 可 能 有 点 麻 烦 。
★首      先        假       设        我       们         有         这       样       一       个        文       本       文       件           sedtest.txt
cat > sedtest.txt
Sed is a stream editor
----------------------
A stream editor is used to perform basic text transformations on an input stream
--------------------------------------------------------------------------------
While in some ways similar to an editor which permits scripted edits (such as ed
)
,
--------------------------------------------------------------------------------
-
-
sed works by making only one pass over the input(s), and is consequently more
-----------------------------------------------------------------------------
efficient. But it is sed's ability to filter text in a pipeline which particular
l
y
--------------------------------------------------------------------------------
-
★输          出            指              定             范              围            的           行            p other types of editors.
sed -e "1,4p" -n sedtest.txt
sed -e "/from/p" -n sedtest.txt
sed -e "1,/from/p" -n sedtest.txt
★在        每          一          行           前         面           增           加       一            个       制           表           符        (^I)
sed "s/^/^I/g" sedtest.txt
注        意            ^I           的           输       入               方       法         是           ctrl-v ctrl-i
单             个                    ^               表               示               行             首
★在            每                一           行           后               面           增         加             --end
sed "s/$/--end/g" sedtest.txt
单             个                    $               表               示               行             尾
★显       示        指        定           模   式       匹       配       行       的       行     号       [/pattern/]=
sed -e '/is/=' sedtest.txt
1
Sed is a stream editor
----------------------
3
A stream editor is used to perform basic text transformations on an input stream
--------------------------------------------------------------------------------
While in some ways similar to an editor which permits scripted edits (such as ed
)
,
--------------------------------------------------------------------------------
-
-
7
sed works by making only one pass over the input(s), and is consequently more
-----------------------------------------------------------------------------
9
efficient. But it is sed's ability to filter text in a pipeline which particular
l
y
--------------------------------------------------------------------------------
-
-
意 思 是 分 析 sedtest.txt , 显 示 那 些 包 含 is 串 的 匹 配 行 的 行 号 , 注 意 11 行 中 出 现 了 is 字 符 串
这 个 输 出 是 面 向 stdout 的 , 如 果 不 做 重 定 向 处 理 , 则 不 影 响 原 来 的 sedtest.txt
★在      匹     配       行    后           面   增       加   文       本       [/pattern/]a 或       者   [address]a
^D
sed -f sedadd.script sedtest.txt
Sed is a stream editor
A stream editor is used to perform basic text transformations on an input stream
While in some ways similar to an editor which permits scripted edits (such as ed
)
,
--------------------------------------------------------------------------------
-
-
sed works by making only one pass over the input(s), and is consequently more
-----------------------------------------------------------------------------
efficient. But it is sed's ability to filter text in a pipeline which particular
l
y
--------------------------------------------------------------------------------
-
-
[scz@ /home/scz/src]> sed -e "a
+++++++++
---------------------------------------------
找 到 包 含 from 字 符 串 的 行 , 在 该 行 的 下 一 行 增 加 +++++++++ 。
这 个 输 出 是 面 向 stdout 的 , 如 果 不 做 重 定 向 处 理 , 则 不 影 响 原 来 的 sedtest.txt
很多人想在命令行上直接完成这个操作而不是多一个 sedadd.script,不幸的是,这需要用?nbsp;
?nbsp;
续                      行                            符                                              ,
    [scz@ /home/scz/src]> sed -e "/from/a
>                                                                                           +++++++++" sedtest.txt
    [scz@ /home/scz/src]> sed -e "a
>                                                                                           +++++++++" sedtest.txt
上      面   这       条   命       令    将   在       所   有       行   后       增   加       一   个       新   行       +++++++++
    [scz@ /home/scz/src]> sed -e "1 a
>                                                                                           +++++++++" sedtest.txt
把 下 面 这 两 行                        copy/paste       到 一 个           shell   命 令 行 上 , 效 果 一 样
+++++++++" sedtest.txt
    [address]a 只              接         受              一           个           地           址        指              定
对于 a 命令,不支持单引号,只能用双引号,而对于 d 命令等其他命令,同时
★删             除       匹           配        行           [/pattern/]d 或              者           [address1][,address2]d
sed -e '/---------------------------------------------/d' sedtest.txt
Sed is a stream editor
A stream editor is used to perform basic text transformations on an input stream
While in some ways similar to an editor which permits scripted edits (such as ed
)
,
sed works by making only one pass over the input(s), and is consequently more
efficient. But it is sed's ability to filter text in a pipeline which particular
l
y
sed -e '6,10d' sedtest.txt
删          除       6-10            行        的       内           容       ,           包           括       6       和           10
sed -e "2d" sedtest.txt
删              除               第                2               行               的               内               容
sed "1,/^$/d" sedtest.txt
删      除       从   第       一       行    到       第   一       个       空   行       之       间     的     所       有   内       容
注 意 这 个 命 令 很 容 易 带 来 意 外 的 结 果 , 当 sedtest.txt 中 从 第 一 行 开 始 并 没 有 空 行 , 则 sed 删
?nbsp;
?nbsp;
sed "1,/from/d" sedtest.txt
删 除 从 第 一 行 到 第 一 个 包 含 from 字 符 串 的 行 之 间 的 所 有 内 容 , 包 括 第 一 个 包 含
from                   字                      符                      串                的                       行                    。
★替         换           匹             配            行              [/pattern/]c 或                  者           [address1][,address2]c
sed -e "/is/c
**********" sedtest.txt
寻    找     所       有       包     含       is       字       符       串      的    匹       配       行       ,       替        换       成   **********
**********
----------------------
**********
--------------------------------------------------------------------------------
While in some ways similar to an editor which permits scripted edits (such as ed
)
,
--------------------------------------------------------------------------------
-
-
**********
-----------------------------------------------------------------------------
**********
--------------------------------------------------------------------------------
-
sed -e "1,11c
**********" sedtest.txt----------------------
在   1-12       行 内 搜 索 所 有                               from        字 符 串 , 分 别 替 换 成 **** 字 符 串
★限             定                范                围               后            的           模               式                匹               配
sed "/But/s/is/are/g" sedtest.txt
对      那   些       包            含       But          字        符       串       的       行       ,       把           is       替       换       成       are
sed "/is/s/t/T/" sedtest.txt
对 那 些 包 含                  is      字 符 串 的 行 , 把 每 行 第 一 个 出 现 的                                                               t 替 换 成 T
sed "/While/,/from/p" sedtest.txt -n
输      出   在           这        两       个         模       式          匹    配       行       之       间           的        所       有       内       容
★指         定       替        换           每         一          行       中        匹       配       的           第        几           次       出       现
sed "s/is/are/5" sedtest.txt
把      每       行       的        is       字           符       串       的       第        5       次       出       现            替       换       成       are
★&                 代                        表                        最                后                       匹                    配
sed "s/^$/(&)/" sedtest.txt
给          所                   有                 空                行               增               加                    一               对            ()
sed "s/is/(&)/g" sedtest.txt
给          所               有                is               字            符               串           外                    增           加            ()
sed "s/.*/(&)/" sedtest.txt
给              所                    有                    行                增                   加               一                    对                ()
sed "/is/s/.*/(&)/" sedtest.txt
给        所        有       包           含           is       字       符           串        的           行       增           加       一           对       ()
★利               用            sed                 修            改           PATH                 环               境           变            量
先                查                看                    PATH                    环                境                   变               量
[scz@ /home/scz/src]> echo $PATH
/usr/bin:/usr/bin:/bin:/usr/local/bin:/sbin:/usr/sbin:/usr/X11R6/bin:.
去                     掉                       尾                    部                        的                       { :/usr/X11R6/bin:. }
[scz@ /home/scz/src]> echo $PATH | sed "s/^(.*):/usr[/]X11R6/bin:[.]$/1/"
/usr/bin:/usr/bin:/bin:/usr/local/bin:/sbin:/usr/sbin
去                         掉                            中                        间                           的                           { :/bin: }
[scz@ /home/scz/src]> echo $PATH | sed "s/^(.*):/bin:(.*)$/12/"
/usr/bin:/usr/bin/usr/local/bin:/sbin:/usr/sbin:/usr/X11R6/bin:.
[/]           表               示               /            失               去            特               殊               意               义
/            同           样               表                示               /            失               去               意               义
1           表        示               子           匹            配           的            第           一               次           出           现
2           表        示               子           匹            配           的            第           二               次           出           现
(.*)                    表                            示                       子                        匹                       配
去        掉        尾           部       的           :        ,       然           后        增           加           新       的           路        径
PATH=`echo $PATH | sed 's/(.*):$/1/'`:$HOME/src
注        意        反           引       号            `       和           单        引       号           '       的           区           别       。


★测            试           并           提               高        sed             命        令               运           行           效           率
time sed -n "1,12p" webkeeper.db > /dev/null
time sed 12q webkeeper.db > /dev/null
可         以           看           出           后            者       比            前           者           效           率           高           。
[address]q 当                  碰       上               指        定       行           时        退           出           sed             执       行
★指                定               输               出            文               件            [address1][,address2]w outputfile
sed "1,10w sed.out" sedtest.txt -n
将      sedtest.txt            中       1-10             行   的       内       容        写       到       sed.out             文       件       中       。
★指                    定                   输                入                   文                 件                      [address]r inputfile
sed "1r sedappend.txt" sedtest.txt
将     sedappend.txt               中 的 内 容 附 加 到                                sedtest.txt          文 件 的 第 一 行 之 后
★替                换               相               应            字               符                [address1][,address2]y/old/new/
sed "y/abcdef/ABCDEF/" sedtest.txt
将 sedtest.txt 中 所 有 的 abcdef 小 写 字 母 替 换 成 ABCDEF 大 写 字 母 。
★!                            号                                的                        使                                   用
sed -e '3,7!d' sedtest.txt
删            除            3-7                 行                之           外                的               所               有           行
sed -e '1,/from/!d' sedtest.txt
找     到       包       含       from        字        符       串       的       行       ,    删       除       其       后       的       所       有       行
★ c              正               则                   表            达               式                c的                  使               用
sed -e ":from:d" sedtest.txt
等                                 价                                于                                    sed -e "/from/d" sedtest.txt
★ sed             命       令           中            正           则       表            达           式           的           复       杂           性
cat > sedtest.txt
^/[}]{.*}[(]$)
^D
如           何        才          能       把           该           行           替       换       成
(]$)/[}]{.*}^[
★转          换    man        手       册   成       普       通       文       本       格   式   (       新   )
man sed | col -b > sed.txt
sed -e "s/^H//g" -e "/^$/d" -e "s/^^I/ /g" -e "s/^I/ /g" sed.txt > sedman
txt
删除所有退格键、空行,把行首的制表符替换成 8 个空格,其余制表符替换成一个空格。
★ sed        的    man       手       册   (   用       的       就       是   上       面   的   方       法   )
NAME
sed - a Stream EDitor
SYNOPSIS
sed [-n] [-V] [--quiet] [--silent] [--version] [--help]
[-e script] [--expression=script]
[-f script-file] [--file=script-file]
[script-if-no-other-script]
[file...]
DEscriptION
Sed is a stream editor. A stream editor is used to per-
form basic text transformations on an input stream (a file
or input from a pipeline). While in some ways similar to
an editor which permits scripted edits (such as ed), sed
works by making only one pass over the input(s), and is
consequently more efficient. But it is sed's ability to
filter text in a pipeline which particularly distinguishes
it from other types of editors.
OPTIONS
Sed may be invoked with the following command-line
options:
-V
--version
Print out the version of sed that is being run and
a copyright notice, then exit.
-h
--help Print a usage message briefly summarizing these
command-line options and the bug-reporting address,
then exit.
-n
--quiet
--silent
By default, sed will print out the pattern space at
the end of each cycle through the script. These
options disable this automatic printing, and sed
will only produce output when explicitly told to
via the p command.
-e script
--expression=script
Add the commands in script to the set of commands
to be run while processing the input.
-f script-file
--file=script-file
Add the commands contained in the file script-file
to the set of commands to be run while processing
the input.
If no -e,-f,--expression, or --file options are given on
the command-line, then the first non-option argument on
the command line is taken to be the script to be executed.
If any command-line parameters remain after processing the
above, these parameters are interpreted as the names of
input files to be processed. A file name of - refers to
the standard input stream. The standard input will pro-
cessed if no file names are specified.
Command Synopsis
This is just a brief synopsis of sed commands to serve as
a reminder to those who already know sed; other documenta-
tion (such as the texinfo document) must be consulted for
fuller descriptions.
Zero-address ``commands''
: label
Label for b and t commands.
#comment
The comment extends until the next newline (or the
end of a -e script fragment).
} The closing bracket of a { } block.
Zero- or One- address commands
= Print the current line number.
a
text Append text, which has each embedded newline pre-
ceeded by a backslash.
i
text Insert text, which has each embedded newline pre-
ceeded by a backslash.
q Immediately quit the sed script without processing
any more input, except that if auto-print is not
diabled the current pattern space will be printed.
r filename
Append text read from filename.
Commands which accept address ranges
{ Begin a block of commands (end with a }).
b label
Branch to label; if label is omitted, branch to end
of script.
t label
If a s/// has done a successful substitution since
the last input line was read and since the last t
command, then branch to label; if label is omitted,
branch to end of script.
c
text Replace the selected lines with text, which has
each embedded newline preceeded by a backslash.
d Delete pattern space. Start next cycle.
D Delete up to the first embedded newline in the pat-
tern space. Start next cycle, but skip reading
from the input if there is still data in the pat-
tern space.
h H Copy/append pattern space to hold space.
g G Copy/append hold space to pattern space.
x Exchange the contents of the hold and pattern
spaces.
l List out the current line in a ``visually unambigu-
ous'' form.
n N Read/append the next line of input into the pattern
space.
p Print the current pattern space.
P Print up to the first embedded newline of the cur-
rent pattern space.
s/regexp/replacement/
Attempt to match regexp against the pattern space.
If successful, replace that portion matched with
replacement. The replacement may contain the spe-
cial character & to refer to that portion of the
pattern space which matched, and the special
escapes 1 through 9 to refer to the corresponding
matching sub-expressions in the regexp.
w filename Write the current pattern space to file-
name.
y/source/dest/
Transliterate the characters in the pattern space
which appear in source to the corresponding charac-
ter in dest.
Addresses
Sed commands can be given with no addresses, in which case
the command will be executed for all input lines; with one
address, in which case the command will only be executed
for input lines which match that address; or with two
addresses, in which case the command will be executed for
all input lines which match the inclusive range of lines
starting from the first address and continuing to the sec-
ond address. Three things to note about address ranges:
the syntax is addr1,addr2 (i.e., the addresses are sepa-
rated by a comma); the line which addr1 matched will
always be accepted, even if addr2 selects an earlier line;
and if addr2 is a regexp, it will not be tested against
the line that addr1 matched.
After the address (or address-range), and before the com-
mand, a ! may be inserted, which specifies that the com-
mand shall only be executed if the address (or address-
range) does not match.
The following address types are supported:
number Match only the specified line number.
first~step
Match every step'th line starting with line first.
For example, ``sed -n 1~2p'' will print all the
odd-numbered lines in the input stream, and the
address 2~5 will match every fifth line, starting
with the second. (This is a GNU extension.)
$ Match the last line.
/regexp/
Match lines matching the regular expression regexp.
cregexpc
Match lines matching the regular expression regexp.
The c may be any character.
Regular expressions
POSIX.2 BREs should be supported, but they aren't com-
pletely yet. The n sequence in a regular expression
matches the newline character. There are also some GNU
extensions. [XXX FIXME: more needs to be said. At the
very least, a reference to another document which
describes what is supported should be given.]
Miscellaneous notes
This version of sed supports a <newline> sequence in all
regular expressions, the replacement part of a substitute
(s) command, and in the source and dest parts of a
transliterate (y) command. The  is stripped, and the
newline is kept.
SEE ALSO
awk(1), ed(1), expr(1), emacs(1), perl(1), tr(1), vi(1),
regex(5) [well, one ought to be written... XXX], sed.info,
any of various books on sed, the sed FAQ
(   http://www.wollery.demon.co.uk/sedtut10.txt,
    http://www.ptug.org/sed/sedfaq.htm).
BUGS
E-mail bug reports to bug-gnu-utils@gnu.org. Be sure to
include the word ``sed'' somewhere in the ``Subject:''
field.


Sed                       学                       习                        笔       记




--------------------------------------------------------------------------------


Table of Contents


1. Sed                               简                              介


2. 定                                               址


3. Sed                               命                              令


4. 选                                               项


5. 元                       字                       符                        集


6. 实                                               例


7. 脚                                                                               本


1. Sed                                              简                              介


sed 是一种在线编辑器,它一次处理一行内容。处理时,把当前处理的行存储在临时缓冲区中,称为“模
式空间”(pattern space),接着用 sed 命令处理缓冲区中的内容,处理完成后,把缓冲区的内容送往
屏幕。接着处理下一行,这样不断重复,直到文件末尾。文件内容并没有改变,除非你使用重定向存储输出。
Sed 主要用来自动编辑一个或多个文件;简化对文件的反复操作;编写转换程序等。以下介绍的是 Gnu 版
本                              的                             Sed 3.02              。


2. 定                                                                               址


可以通过定址来定位你所希望编辑的行,该地址用数字构成,用逗号分隔的两个行数表示以这两行为起止
的行的范围(包括行数表示的那两行)。如 1,3 表示 1,2,3 行,美元符号($)表示最后一行。范围可以
通    过    数      据   ,       正   则       表    达       式   或   者       二   者       结   合       的   方       式       确       定   。


3. Sed                                                            命                                                           令


调         用          sed             命        令           有           两           种           形           式           :


sed [options] 'command' file(s)


sed [options] -f scriptfile file(s)


a


在         当          前       行           后        面           加       入           一           行           文           本       。


b lable


分 支 到 脚 本 中 带 有 标 记 的 地 方 , 如 果 分 支 不 存 在 则 分 支 到 脚 本 的 末 尾 。


c


用         新          的       文           本        改           变       本           行           的           文           本       。


d


从        模       板       块           (       Pattern space            )       位           置       删           除       行       。


D


删            除           模           板            块           的           第           一               行           。


i


在            当           前           行            上           面           插           入           文               本           。


h


拷     贝          模   板       块       的       内        容       到       内       存       中       的       缓       冲       区       。


H


追     加          模       板       块       的        内       容       到       内       存           中   的           缓       冲       区


g
获 得 内 存 缓 冲 区 的 内 容 , 并 替 代 当 前 模 板 块 中 的 文 本 。


G


获 得 内 存 缓 冲 区 的 内 容 , 并 追 加 到 当 前 模 板 块 文 本 的 后 面 。


l


列         表       不           能       打           印       字           符       的           清       单   。


n


读 取 下 一 个 输 入 行 , 用 下 一 个 命 令 处 理 新 的 行 而 不 是 用 第 一 个 命 令 。


N


追加下一个输入行到模板块后面并在二者间嵌入一个新行,改变当前行号码。


p


打             印               模               板               块               的               行       。


P                 (                       大                       写                       )


打         印           模           板           块           的               第           一           行   。


q


退                                 出                                   Sed                             。


r file


从                 file                    中                       读                       行           。


t label


if 分支,从最后一行开始,条件一旦满足或者 T,t 命令,将导致分支到带有标号的命令处,或者到脚本
的                                 末                                       尾                           。


T label


错误分支,从最后一行开始,一旦发生错误或者 T,t 命令,将导致分支到带有标号的命令处,或者到脚
本                         的                           末                           尾                   。
w file


写            并        追               加           模       板           块               到       file               末            尾        。


W file


写        并       追        加           模       板       块       的       第       一           行   到           file        末           尾    。


!


表   示        后   面        的       命       令   对       所   有   没       有       被   选       定   的       行       发       生   作        用   。


s/re/string


用            string               替           换           正           则           表           达             式             re           。


=


打                印                        当               前                   行               号                       码                。


#


把        注       释            扩           展       到       下       一           个       换       行           符           以        前       。


以                下                的                   是           替                   换               标                   记


g            表                示               行           内               全               面           替                   换            。


p                     表                       示                   打                       印                       行                    。


w            表        示               把           行           写           入           一           个           文               件        。


x   表        示   互        换       模       板   块       中   的       文       本       和       缓   冲   区        中         的    文       本    。


y 表 示 把 一 个 字 符 翻 译 为 另 外 的 字 符 ( 但 是 不 用 于 正 则 表 达 式 )


4. 选                                                                                                                                   项


-e command, --expression=command


允                     许                       多                   台                       编                       辑                    。


-h, --help
打      印        帮       助         ,       并       显       示       bug         列       表       的       地       址       。


-n, --quiet, --silent


取                   消                     默               认                       输               出                   。


-f, --filer=script-file


引           导                 sed             脚               本               文           件           名               。


-V, --version


打          印              版               本           和           版               权         信             息           。


5. 元                                      字                                       符                                   集


^锚     定    行   的       开     始       如   :   /^sed/      匹       配   所   有       以   sed     开   头   的       行   。


$锚     定   行    的       结     束       如   :   /sed$/      匹   配       所   有       以   sed     结   尾   的       行   。


. 匹 配 一 个 非 换 行 符 的 字 符 如 : /s.d/ 匹 配 s 后 接 一 个 任 意 字 符 , 然 后 是 d 。


* 匹 配 零 或 多 个 字 符 如 : /*sed/ 匹 配 所 有 模 板 是 一 个 或 多 个 空 格 后 紧 跟 sed 的 行 。


[] 匹 配 一 个 指 定 范 围 内 的 字 符 , 如 /[Ss]ed/ 匹 配                                                     sed   和   Sed 。


[^] 匹配一个不在指定范围内的字符,如:/[^A-RT-Z]ed/匹配不包含 A-R 和 T-Z 的一个字母开头,紧
跟                       ed                     的                          行                       。


(..) 保 存 匹 配 的 字 符 , 如 s/(love)able/1rs , loveable 被 替 换 成 lovers 。


& 保 存 搜 索 字 符 用 来 替 换 其 他 字 符 , 如 s/love/**&**/ , love 这 成 **love** 。


< 锚 定 单 词 的 开 始 , 如 :/<love/ 匹 配 包 含 以 love 开 头 的 单 词 的 行 。


> 锚 定 单 词 的 结 束 , 如 /love>/ 匹 配 包 含 以 love 结 尾 的 单 词 的 行 。


x{m} 重 复 字 符 x , m 次 , 如 : /0{5}/ 匹 配 包 含 5 个 o 的 行 。


x{m,} 重 复 字 符 x, 至 少 m 次 , 如 : /o{5,}/ 匹 配 至 少 有 5 个 o 的 行 。


x{m,n} 重 复 字 符 x , 至 少 m 次 , 不 多 于 n 次 , 如 : /o{5,10}/ 匹 配 5--10 个 o 的 行 。
6. 实                                                                                                                    例


删              除                   :                 d                       命                   令


$ sed '2d' example-----        删       除        example          文       件       的       第           二          行       。


$ sed '2,$d' example----- 删 除              example   文 件 的 第 二 行 到 末 尾 所 有 行 。


$ sed '$d' example-----        删       除       example       文       件       的       最       后       一          行       。


$ sed '/test/'d example-----       删   除       example       文   件       所   有   包       含       test       的       行   。


替              换                   :                 s                       命                   令


$ sed 's/test/mytest/g' example-----在整行范围内把 test 替换为 mytest。如果没有 g 标记,则只有
每      行   第       一       个       匹       配     的       test        被       替   换           成          mytest          。


$ sed -n 's/^test/mytest/p' example-----(-n)选项和 p 标志一起使用表示只打印那些发生替换的行。
也 就 是 说 , 如 果 某 一 行 开 头 的 test 被 替 换 成 mytest , 就 打 印 它 。


$ sed 's/^192.168.0.1/&localhost/' example-----&符号表示替换换字符串中被找到的部份。所有以
192.168.0.1 开 头 的 行 都 会 被 替 换 成 它 自 已 加 localhost , 变 成 192.168.0.1localhost 。


$ sed -n 's/(love)able/1rs/p' example-----love 被 标 记 为 1 , 所 有 loveable 会 被 替 换 成
lovers     ,    而          且   替           换    的        行       会       被       打       印         出            来       。


$ sed 's#10#100#g' example-----不论什么字符,紧跟着 s 命令的都被认为是新的分隔符,所以,
“ #” 在 这 里 是 分 隔 符 , 代 替 了 默 认 的 “ /” 分 隔 符 。 表 示 把 所 有 10 替 换 成 100 。


选          定           行           的            范            围               :           逗               号


$ sed -n '/test/,/check/p' example-----所有在模板 test 和 check 所确定的范围内的行都被打印。


$ sed -n '5,/^test/p' example-----打印从第五行开始到第一个包含以 test 开始的行之间的所有行。


$ sed '/test/,/check/s/$/sed test/' example-----对于模板 test 和 west 之间的行,每行的末尾用字
符               串                      sed test                      替                       换                          。


多          点               编           辑             :               e               命                  令


$ sed -e '1,5d' -e 's/test/check/' example-----(-e)选项允许在同一行里执行多条命令。如例子所示 ,
第一条命令删除 1 至 5 行,第二条命令用 check 替换 test。命令的执行顺序对结果有影响。如果两个命令
都 是 替 换 命 令 , 那 么 第 一 个 替 换 命 令 将 影 响 第 二 个 替 换 命 令 的 结 果 。
$ sed --expression='s/test/check/' --expression='/love/d' example----- 一 个 比 -e 更 好 的 命 令
是      --expression               。           它        能       给           sed             表           达       式           赋       值     。


从            文                件               读                入               :               r               命               令


$ sed '/test/r file' example-----file 里的内容被读进来,显示在与 test 匹配的行后面,如果匹配多行,
则     file       的        内       容       将       显        示       在       所       有       匹       配           行       的       下    面    。


写                入                文                件                   :               w                   命                   令


$ sed -n '/test/w file' example----- 在 example 中 所 有 包 含 test 的 行 都 被 写 入 file 里 。


追                加                命                令                   :               a                   命                   令


$ sed '/^test/a--->this is a example' example<-----'this is a example'被追加到以 test 开头
的    行       后       面    ,       sed     要        求       命       令       a       后   面           有       一       个   反       斜    杠    。


插                     入                       :                        i                       命                       令


$ sed '/test/i


new line


-------------------------' example


如 果 test 被 匹 配 , 则 把 反 斜 杠 后 面 的 文 本 插 入 到 匹 配 行 的 前 面 。


下                 一                   个                    :                   n                       命                   令


$ sed '/test/{ n; s/aa/bb/; }' example-----如果 test 被匹配,则移动到匹配行的下一行,替换这一
行    的       aa       ,       变       为       bb       ,       并       打       印       该       行       ,       然       后       继    续    。


变                     形                       :                        y                       命                       令


$ sed '1,10y/abcde/ABCDE/' example-----把 1--10 行内所有 abcde 转变为大写,注意,正则表达
式        元           字        符           不           能        使           用           这           个           命           令       。


退                     出                       :                        q                       命                       令


$ sed '10q' example-----                  打        印       完       第       10          行       后           ,       退       出       sed   。


保        持           和        获           取           :        h           命           令           和           G           命       令
$ sed -e '/test/h' -e '$G example-----在 sed 处理文件的时候,每一行都被保存在一个叫模式空间的
临时缓冲区中,除非行被删除或者输出被取消,否则所有被处理的行都将打印在屏幕上。接着模式空间被
清空,并存入新的一行等待处理。在这个例子里,匹配 test 的行被找到后,将存入模式空间,h 命令将其
复制并存入一个称为保持缓存区的特殊缓冲区内。第二条语句的意思是,当到达最后一行后, G 命令取出
保持缓冲区的行,然后把它放回模式空间中,且追加到现在已经存在于模式空间中的行的末尾。在这个例
子 中 就 是 追 加 到 最 后 一 行 。 简 单 来 说 , 任 何 包 含 test 的 行 都 被 复 制 并 追 加 到 该 文 件 的 末 尾 。


保      持    和       互   换       :   h       命   令     和      x       命       令


$ sed -e '/test/h' -e '/check/x' example -----互换模式空间和保持缓冲区的内容。也就是把包含 test
与           check           的               行        互               换           。


7. 脚                                                                             本


Sed 脚本是一个 sed 的命令清单,启动 Sed 时以-f 选项引导脚本文件名。Sed 对于脚本中输入的命令非
常挑剔,在命令的末尾不能有任何空白或文本,如果在一行中有多个命令,要用分号分隔。以#开头的行
为      注        释       行       ,       且       不     能          跨       行       。

More Related Content

Featured

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Sed 命令详解

  • 1. Sed 命令详解 1.sed -n '2'p filename 打 印 文 件 的 第 二 行 。 2.sed -n '1,3'p filename 打 印 文 件 的 1 到 3 行 3. sed -n '/Neave/'p filename 打 印 匹 配 Neave 的 行 ( 模 糊 匹 配 ) 4. sed -n '4,/The/'p filename 在 第 4 行 查 询 模 式 The 5. sed -n '1,$'p filename 打 印 整 个 文 件 , $ 表 示 最 后 一 行 。 6. sed -n '/.*ing/'p filename 匹 配 任 意 字 母 , 并 以 ing 结 尾 的 单 词 ( 点 号 不 能 少 ) 7 sed -n / -e '/music/'= filename 打印匹配行的行号,-e 会打印文件的内容,同时在匹配行的前面标志行号。-n 只打印出实际的行号。 8.sed -n -e '/music/'p -e '/music/'= filename 打 印 匹 配 的 行 和 行 号 , 行 号 在 内 容 的 下 面 9.sed '/company/' a "Then suddenly it happend" filename 选择含有 company 的行,将后面的内容"Then suddenly it happend"加入下一行。注意:它并不改变 文 件 , 所 有 操 作 在 缓 冲 区 , 如 果 要 保 存 输 出 , 重 定 向 到 一 个 文 件 。 10. sed '/company/' i "Then suddenly it happend" filename 同 9 , 只 是 在 匹 配 的 行 前 插 入 11.sed '/company/' c "Then suddenly it happend" filename 用 "Then suddenly it happend" 替 换 匹 配 company 的 行 的 内 容 。 12.sed '1'd ( '1,3'd '$'d '/Neave/'d) filename 删 除 第 一 行 (1 到 3 行 , 最 后 一 行 , 匹 配 Neave 的 行 ) 13.[ address [ , address]] s/ pattern-to-find /replacement-pattern/[g p w n] s 选项通知 s e d 这是一个替换操作,并查询 pattern-to-find,成功后用 replacement-pattern 替换它。 替 换 选 项 如 下 : g缺省情况下只替换第一次出现模 式, 使用 g 选 项替 换全 局所 有出 现模 式。 p 缺省 s e d 将所有被替换行写入标准输出,加 p 选项将使- n 选项无效。- n 选项不打印输出结果。 w 文件名使用此选项将输出定向到一个文件。 (注意只将匹配替换的行写入文件,而不是整个内容 ) 14.sed s'/nurse/"hello "&/' filename 将 'hello ' 增 加 到 'nurse' 的 前 面 。 15. sed '/company/r append.txt' filename 在 匹 配 company 的 行 的 下 一 行 开 始 加 入 文 件 append.txt 的 内 容 。 16. sed '/company/'q filename 首 次 匹 配 company 后 就 退 出 sed 程 序 只 所 以 看 sed 命 令 , 是 因 为 我 遇 到 了 这 个 一 个 问 题 。 网上有很多教程,他们发表了很多程序代码,但是作者为了解释方便,都对程序作了行号编码,就像下面 这 样 :
  • 2. 码 :: 1:#!/bin/bash 2:#rename file extesions 3:# 4:# rfe old_extensions new_extension 假 设 这 个 文 件 名 是 tmp , 那 么 我 们 可 以 使 用 下 面 的 命 令 来 去 掉 这 个 行 号 和 冒 号 ( : ) 代 码 :: sed -e s'/^[0-9]{1,}://g' tmp 不过上面的命令的命令有一个缺点,那就是如果这个行号不是数字开头,而是有空格的话,那就需要修改 匹配规则,规则应该修改为匹配第一个非空白字符是数字开始,后面接一个冒号的配对。命令如下: 代 码 :: sed -e s'/^[^0-9a-zA-Z]*[0-9]{1,}://g' tmp 这令我很兴奋,于是想看看 sed 到底有多厉害,看了以后,明白的是不是 sed 有多厉害,就像 awk 一样, 他 们 只 是 把 正 规 表 达 式 用 到 了 极 致 。 以 Redhat6.0 为 测 试 环 境 事 实 上 在 solaris 下 的 sed 命 令 要 比 linux 强 , 但 因 为 没 有 测 试 环 境 , 我 这 里 只 给 在 linux 下 经 过 测 试 的 用 法 。 ★命 令 行 参 数 简 介 ★首 先 假 设 我 们 有 这 样 一 个 文 本 文 件 sedtest.txt ★输 出 指 定 范 围 的 行 p ★在 每 一 行 前 面 增 加 一 个 制 表 符 (^I) ★在 每 一 行 后 面 增 加 --end ★显 示 指 定 模 式 匹 配 行 的 行 号 [/pattern/]= ★在 匹 配 行 后 面 增 加 文 本 [/pattern/]a 或 者 [address]a ★删 除 匹 配 行 [/pattern/]d 或 者 [address1][,address2]d ★替 换 匹 配 行 [/pattern/]c 或 者 [address1][,address2]c ★在 匹 配 行 前 面 插 入 文 本 [/pattern/]i 或 者 [address]i ★替 换 匹 配 串 ( 注 意 不 再 是 匹 配 行 ) [addr1][,addr2]s/old/new/g ★限 定 范 围 后 的 模 式 匹 配 ★指 定 替 换 每 一 行 中 匹 配 的 第 几 次 出 现
  • 3. ★& 代 表 最 后 匹 配 ★利 用 sed 修 改 PATH 环 境 变 量 ★测 试 并 提 高 sed 命 令 运 行 效 率 ★指 定 输 出 文 件 [address1][,address2]w outputfile ★指 定 输 入 文 件 [address]r inputfile ★替 换 相 应 字 符 [address1][,address2]y/old/new/ ★! 号 的 使 用 ★ c 正 则 表 达 式 c的 使 用 ★ sed 命 令 中 正 则 表 达 式 的 复 杂 性 ★转 换 man 手 册 成 普 通 文 本 格 式 ( 新 ) ★ sed 的 man 手 册 ( 用 的 就 是 上 面 的 方 法 ) ★命 令 行 参 数 简 介 sed -e script 指 定 sed 编 辑 命 令 -f scriptfile 指 定 的 文 件 中 是 sed 编 辑 命 令 -n 寂 静 模 式 , 抑 制 来 自 sed 命 令 执 行 过 程 中 的 冗 余 输 出 信 息 , 比 如 只 显 示 那 些 被 改 变 的 行 。 不 明 白 ? 不 要 紧 , 把 这 些 肮 脏 丢 到 一 边 , 跟 我 往 下 走 , 不 过 下 面 的 介 绍 里 不 包 括 正 则 表 达 式 的 解 释 , 如 果 你 不 明 白 , 可 能 有 点 麻 烦 。 ★首 先 假 设 我 们 有 这 样 一 个 文 本 文 件 sedtest.txt cat > sedtest.txt Sed is a stream editor ---------------------- A stream editor is used to perform basic text transformations on an input stream -------------------------------------------------------------------------------- While in some ways similar to an editor which permits scripted edits (such as ed ) , -------------------------------------------------------------------------------- - - sed works by making only one pass over the input(s), and is consequently more ----------------------------------------------------------------------------- efficient. But it is sed's ability to filter text in a pipeline which particular l y -------------------------------------------------------------------------------- - ★输 出 指 定 范 围 的 行 p other types of editors. sed -e "1,4p" -n sedtest.txt sed -e "/from/p" -n sedtest.txt sed -e "1,/from/p" -n sedtest.txt ★在 每 一 行 前 面 增 加 一 个 制 表 符 (^I)
  • 4. sed "s/^/^I/g" sedtest.txt 注 意 ^I 的 输 入 方 法 是 ctrl-v ctrl-i 单 个 ^ 表 示 行 首 ★在 每 一 行 后 面 增 加 --end sed "s/$/--end/g" sedtest.txt 单 个 $ 表 示 行 尾 ★显 示 指 定 模 式 匹 配 行 的 行 号 [/pattern/]= sed -e '/is/=' sedtest.txt 1 Sed is a stream editor ---------------------- 3 A stream editor is used to perform basic text transformations on an input stream -------------------------------------------------------------------------------- While in some ways similar to an editor which permits scripted edits (such as ed ) , -------------------------------------------------------------------------------- - - 7 sed works by making only one pass over the input(s), and is consequently more ----------------------------------------------------------------------------- 9 efficient. But it is sed's ability to filter text in a pipeline which particular l y -------------------------------------------------------------------------------- - - 意 思 是 分 析 sedtest.txt , 显 示 那 些 包 含 is 串 的 匹 配 行 的 行 号 , 注 意 11 行 中 出 现 了 is 字 符 串 这 个 输 出 是 面 向 stdout 的 , 如 果 不 做 重 定 向 处 理 , 则 不 影 响 原 来 的 sedtest.txt ★在 匹 配 行 后 面 增 加 文 本 [/pattern/]a 或 者 [address]a ^D sed -f sedadd.script sedtest.txt Sed is a stream editor A stream editor is used to perform basic text transformations on an input stream While in some ways similar to an editor which permits scripted edits (such as ed ) , -------------------------------------------------------------------------------- - - sed works by making only one pass over the input(s), and is consequently more
  • 5. ----------------------------------------------------------------------------- efficient. But it is sed's ability to filter text in a pipeline which particular l y -------------------------------------------------------------------------------- - - [scz@ /home/scz/src]> sed -e "a +++++++++ --------------------------------------------- 找 到 包 含 from 字 符 串 的 行 , 在 该 行 的 下 一 行 增 加 +++++++++ 。 这 个 输 出 是 面 向 stdout 的 , 如 果 不 做 重 定 向 处 理 , 则 不 影 响 原 来 的 sedtest.txt 很多人想在命令行上直接完成这个操作而不是多一个 sedadd.script,不幸的是,这需要用?nbsp; ?nbsp; 续 行 符 , [scz@ /home/scz/src]> sed -e "/from/a > +++++++++" sedtest.txt [scz@ /home/scz/src]> sed -e "a > +++++++++" sedtest.txt 上 面 这 条 命 令 将 在 所 有 行 后 增 加 一 个 新 行 +++++++++ [scz@ /home/scz/src]> sed -e "1 a > +++++++++" sedtest.txt 把 下 面 这 两 行 copy/paste 到 一 个 shell 命 令 行 上 , 效 果 一 样 +++++++++" sedtest.txt [address]a 只 接 受 一 个 地 址 指 定 对于 a 命令,不支持单引号,只能用双引号,而对于 d 命令等其他命令,同时 ★删 除 匹 配 行 [/pattern/]d 或 者 [address1][,address2]d sed -e '/---------------------------------------------/d' sedtest.txt Sed is a stream editor A stream editor is used to perform basic text transformations on an input stream While in some ways similar to an editor which permits scripted edits (such as ed ) , sed works by making only one pass over the input(s), and is consequently more efficient. But it is sed's ability to filter text in a pipeline which particular l y sed -e '6,10d' sedtest.txt 删 除 6-10 行 的 内 容 , 包 括 6 和 10 sed -e "2d" sedtest.txt 删 除 第 2 行 的 内 容 sed "1,/^$/d" sedtest.txt 删 除 从 第 一 行 到 第 一 个 空 行 之 间 的 所 有 内 容 注 意 这 个 命 令 很 容 易 带 来 意 外 的 结 果 , 当 sedtest.txt 中 从 第 一 行 开 始 并 没 有 空 行 , 则 sed 删
  • 6. ?nbsp; ?nbsp; sed "1,/from/d" sedtest.txt 删 除 从 第 一 行 到 第 一 个 包 含 from 字 符 串 的 行 之 间 的 所 有 内 容 , 包 括 第 一 个 包 含 from 字 符 串 的 行 。 ★替 换 匹 配 行 [/pattern/]c 或 者 [address1][,address2]c sed -e "/is/c **********" sedtest.txt 寻 找 所 有 包 含 is 字 符 串 的 匹 配 行 , 替 换 成 ********** ********** ---------------------- ********** -------------------------------------------------------------------------------- While in some ways similar to an editor which permits scripted edits (such as ed ) , -------------------------------------------------------------------------------- - - ********** ----------------------------------------------------------------------------- ********** -------------------------------------------------------------------------------- - sed -e "1,11c **********" sedtest.txt---------------------- 在 1-12 行 内 搜 索 所 有 from 字 符 串 , 分 别 替 换 成 **** 字 符 串 ★限 定 范 围 后 的 模 式 匹 配 sed "/But/s/is/are/g" sedtest.txt 对 那 些 包 含 But 字 符 串 的 行 , 把 is 替 换 成 are sed "/is/s/t/T/" sedtest.txt 对 那 些 包 含 is 字 符 串 的 行 , 把 每 行 第 一 个 出 现 的 t 替 换 成 T sed "/While/,/from/p" sedtest.txt -n 输 出 在 这 两 个 模 式 匹 配 行 之 间 的 所 有 内 容 ★指 定 替 换 每 一 行 中 匹 配 的 第 几 次 出 现 sed "s/is/are/5" sedtest.txt 把 每 行 的 is 字 符 串 的 第 5 次 出 现 替 换 成 are ★& 代 表 最 后 匹 配 sed "s/^$/(&)/" sedtest.txt 给 所 有 空 行 增 加 一 对 () sed "s/is/(&)/g" sedtest.txt 给 所 有 is 字 符 串 外 增 加 () sed "s/.*/(&)/" sedtest.txt 给 所 有 行 增 加 一 对 ()
  • 7. sed "/is/s/.*/(&)/" sedtest.txt 给 所 有 包 含 is 字 符 串 的 行 增 加 一 对 () ★利 用 sed 修 改 PATH 环 境 变 量 先 查 看 PATH 环 境 变 量 [scz@ /home/scz/src]> echo $PATH /usr/bin:/usr/bin:/bin:/usr/local/bin:/sbin:/usr/sbin:/usr/X11R6/bin:. 去 掉 尾 部 的 { :/usr/X11R6/bin:. } [scz@ /home/scz/src]> echo $PATH | sed "s/^(.*):/usr[/]X11R6/bin:[.]$/1/" /usr/bin:/usr/bin:/bin:/usr/local/bin:/sbin:/usr/sbin 去 掉 中 间 的 { :/bin: } [scz@ /home/scz/src]> echo $PATH | sed "s/^(.*):/bin:(.*)$/12/" /usr/bin:/usr/bin/usr/local/bin:/sbin:/usr/sbin:/usr/X11R6/bin:. [/] 表 示 / 失 去 特 殊 意 义 / 同 样 表 示 / 失 去 意 义 1 表 示 子 匹 配 的 第 一 次 出 现 2 表 示 子 匹 配 的 第 二 次 出 现 (.*) 表 示 子 匹 配 去 掉 尾 部 的 : , 然 后 增 加 新 的 路 径 PATH=`echo $PATH | sed 's/(.*):$/1/'`:$HOME/src 注 意 反 引 号 ` 和 单 引 号 ' 的 区 别 。 ★测 试 并 提 高 sed 命 令 运 行 效 率 time sed -n "1,12p" webkeeper.db > /dev/null time sed 12q webkeeper.db > /dev/null 可 以 看 出 后 者 比 前 者 效 率 高 。 [address]q 当 碰 上 指 定 行 时 退 出 sed 执 行 ★指 定 输 出 文 件 [address1][,address2]w outputfile sed "1,10w sed.out" sedtest.txt -n 将 sedtest.txt 中 1-10 行 的 内 容 写 到 sed.out 文 件 中 。 ★指 定 输 入 文 件 [address]r inputfile sed "1r sedappend.txt" sedtest.txt 将 sedappend.txt 中 的 内 容 附 加 到 sedtest.txt 文 件 的 第 一 行 之 后 ★替 换 相 应 字 符 [address1][,address2]y/old/new/ sed "y/abcdef/ABCDEF/" sedtest.txt 将 sedtest.txt 中 所 有 的 abcdef 小 写 字 母 替 换 成 ABCDEF 大 写 字 母 。 ★! 号 的 使 用 sed -e '3,7!d' sedtest.txt 删 除 3-7 行 之 外 的 所 有 行 sed -e '1,/from/!d' sedtest.txt 找 到 包 含 from 字 符 串 的 行 , 删 除 其 后 的 所 有 行 ★ c 正 则 表 达 式 c的 使 用 sed -e ":from:d" sedtest.txt 等 价 于 sed -e "/from/d" sedtest.txt ★ sed 命 令 中 正 则 表 达 式 的 复 杂 性
  • 8. cat > sedtest.txt ^/[}]{.*}[(]$) ^D 如 何 才 能 把 该 行 替 换 成 (]$)/[}]{.*}^[ ★转 换 man 手 册 成 普 通 文 本 格 式 ( 新 ) man sed | col -b > sed.txt sed -e "s/^H//g" -e "/^$/d" -e "s/^^I/ /g" -e "s/^I/ /g" sed.txt > sedman txt 删除所有退格键、空行,把行首的制表符替换成 8 个空格,其余制表符替换成一个空格。 ★ sed 的 man 手 册 ( 用 的 就 是 上 面 的 方 法 ) NAME sed - a Stream EDitor SYNOPSIS sed [-n] [-V] [--quiet] [--silent] [--version] [--help] [-e script] [--expression=script] [-f script-file] [--file=script-file] [script-if-no-other-script] [file...] DEscriptION Sed is a stream editor. A stream editor is used to per- form basic text transformations on an input stream (a file or input from a pipeline). While in some ways similar to an editor which permits scripted edits (such as ed), sed works by making only one pass over the input(s), and is consequently more efficient. But it is sed's ability to filter text in a pipeline which particularly distinguishes it from other types of editors. OPTIONS Sed may be invoked with the following command-line options: -V --version Print out the version of sed that is being run and a copyright notice, then exit. -h --help Print a usage message briefly summarizing these command-line options and the bug-reporting address, then exit. -n --quiet --silent By default, sed will print out the pattern space at the end of each cycle through the script. These
  • 9. options disable this automatic printing, and sed will only produce output when explicitly told to via the p command. -e script --expression=script Add the commands in script to the set of commands to be run while processing the input. -f script-file --file=script-file Add the commands contained in the file script-file to the set of commands to be run while processing the input. If no -e,-f,--expression, or --file options are given on the command-line, then the first non-option argument on the command line is taken to be the script to be executed. If any command-line parameters remain after processing the above, these parameters are interpreted as the names of input files to be processed. A file name of - refers to the standard input stream. The standard input will pro- cessed if no file names are specified. Command Synopsis This is just a brief synopsis of sed commands to serve as a reminder to those who already know sed; other documenta- tion (such as the texinfo document) must be consulted for fuller descriptions. Zero-address ``commands'' : label Label for b and t commands. #comment The comment extends until the next newline (or the end of a -e script fragment). } The closing bracket of a { } block. Zero- or One- address commands = Print the current line number. a text Append text, which has each embedded newline pre- ceeded by a backslash. i text Insert text, which has each embedded newline pre- ceeded by a backslash. q Immediately quit the sed script without processing any more input, except that if auto-print is not diabled the current pattern space will be printed. r filename
  • 10. Append text read from filename. Commands which accept address ranges { Begin a block of commands (end with a }). b label Branch to label; if label is omitted, branch to end of script. t label If a s/// has done a successful substitution since the last input line was read and since the last t command, then branch to label; if label is omitted, branch to end of script. c text Replace the selected lines with text, which has each embedded newline preceeded by a backslash. d Delete pattern space. Start next cycle. D Delete up to the first embedded newline in the pat- tern space. Start next cycle, but skip reading from the input if there is still data in the pat- tern space. h H Copy/append pattern space to hold space. g G Copy/append hold space to pattern space. x Exchange the contents of the hold and pattern spaces. l List out the current line in a ``visually unambigu- ous'' form. n N Read/append the next line of input into the pattern space. p Print the current pattern space. P Print up to the first embedded newline of the cur- rent pattern space. s/regexp/replacement/ Attempt to match regexp against the pattern space. If successful, replace that portion matched with replacement. The replacement may contain the spe- cial character & to refer to that portion of the pattern space which matched, and the special escapes 1 through 9 to refer to the corresponding matching sub-expressions in the regexp. w filename Write the current pattern space to file- name. y/source/dest/ Transliterate the characters in the pattern space which appear in source to the corresponding charac- ter in dest.
  • 11. Addresses Sed commands can be given with no addresses, in which case the command will be executed for all input lines; with one address, in which case the command will only be executed for input lines which match that address; or with two addresses, in which case the command will be executed for all input lines which match the inclusive range of lines starting from the first address and continuing to the sec- ond address. Three things to note about address ranges: the syntax is addr1,addr2 (i.e., the addresses are sepa- rated by a comma); the line which addr1 matched will always be accepted, even if addr2 selects an earlier line; and if addr2 is a regexp, it will not be tested against the line that addr1 matched. After the address (or address-range), and before the com- mand, a ! may be inserted, which specifies that the com- mand shall only be executed if the address (or address- range) does not match. The following address types are supported: number Match only the specified line number. first~step Match every step'th line starting with line first. For example, ``sed -n 1~2p'' will print all the odd-numbered lines in the input stream, and the address 2~5 will match every fifth line, starting with the second. (This is a GNU extension.) $ Match the last line. /regexp/ Match lines matching the regular expression regexp. cregexpc Match lines matching the regular expression regexp. The c may be any character. Regular expressions POSIX.2 BREs should be supported, but they aren't com- pletely yet. The n sequence in a regular expression matches the newline character. There are also some GNU extensions. [XXX FIXME: more needs to be said. At the very least, a reference to another document which describes what is supported should be given.] Miscellaneous notes This version of sed supports a <newline> sequence in all regular expressions, the replacement part of a substitute (s) command, and in the source and dest parts of a transliterate (y) command. The is stripped, and the
  • 12. newline is kept. SEE ALSO awk(1), ed(1), expr(1), emacs(1), perl(1), tr(1), vi(1), regex(5) [well, one ought to be written... XXX], sed.info, any of various books on sed, the sed FAQ ( http://www.wollery.demon.co.uk/sedtut10.txt, http://www.ptug.org/sed/sedfaq.htm). BUGS E-mail bug reports to bug-gnu-utils@gnu.org. Be sure to include the word ``sed'' somewhere in the ``Subject:'' field. Sed 学 习 笔 记 -------------------------------------------------------------------------------- Table of Contents 1. Sed 简 介 2. 定 址 3. Sed 命 令 4. 选 项 5. 元 字 符 集 6. 实 例 7. 脚 本 1. Sed 简 介 sed 是一种在线编辑器,它一次处理一行内容。处理时,把当前处理的行存储在临时缓冲区中,称为“模 式空间”(pattern space),接着用 sed 命令处理缓冲区中的内容,处理完成后,把缓冲区的内容送往 屏幕。接着处理下一行,这样不断重复,直到文件末尾。文件内容并没有改变,除非你使用重定向存储输出。 Sed 主要用来自动编辑一个或多个文件;简化对文件的反复操作;编写转换程序等。以下介绍的是 Gnu 版 本 的 Sed 3.02 。 2. 定 址 可以通过定址来定位你所希望编辑的行,该地址用数字构成,用逗号分隔的两个行数表示以这两行为起止
  • 13. 的行的范围(包括行数表示的那两行)。如 1,3 表示 1,2,3 行,美元符号($)表示最后一行。范围可以 通 过 数 据 , 正 则 表 达 式 或 者 二 者 结 合 的 方 式 确 定 。 3. Sed 命 令 调 用 sed 命 令 有 两 种 形 式 : sed [options] 'command' file(s) sed [options] -f scriptfile file(s) a 在 当 前 行 后 面 加 入 一 行 文 本 。 b lable 分 支 到 脚 本 中 带 有 标 记 的 地 方 , 如 果 分 支 不 存 在 则 分 支 到 脚 本 的 末 尾 。 c 用 新 的 文 本 改 变 本 行 的 文 本 。 d 从 模 板 块 ( Pattern space ) 位 置 删 除 行 。 D 删 除 模 板 块 的 第 一 行 。 i 在 当 前 行 上 面 插 入 文 本 。 h 拷 贝 模 板 块 的 内 容 到 内 存 中 的 缓 冲 区 。 H 追 加 模 板 块 的 内 容 到 内 存 中 的 缓 冲 区 g
  • 14. 获 得 内 存 缓 冲 区 的 内 容 , 并 替 代 当 前 模 板 块 中 的 文 本 。 G 获 得 内 存 缓 冲 区 的 内 容 , 并 追 加 到 当 前 模 板 块 文 本 的 后 面 。 l 列 表 不 能 打 印 字 符 的 清 单 。 n 读 取 下 一 个 输 入 行 , 用 下 一 个 命 令 处 理 新 的 行 而 不 是 用 第 一 个 命 令 。 N 追加下一个输入行到模板块后面并在二者间嵌入一个新行,改变当前行号码。 p 打 印 模 板 块 的 行 。 P ( 大 写 ) 打 印 模 板 块 的 第 一 行 。 q 退 出 Sed 。 r file 从 file 中 读 行 。 t label if 分支,从最后一行开始,条件一旦满足或者 T,t 命令,将导致分支到带有标号的命令处,或者到脚本 的 末 尾 。 T label 错误分支,从最后一行开始,一旦发生错误或者 T,t 命令,将导致分支到带有标号的命令处,或者到脚 本 的 末 尾 。
  • 15. w file 写 并 追 加 模 板 块 到 file 末 尾 。 W file 写 并 追 加 模 板 块 的 第 一 行 到 file 末 尾 。 ! 表 示 后 面 的 命 令 对 所 有 没 有 被 选 定 的 行 发 生 作 用 。 s/re/string 用 string 替 换 正 则 表 达 式 re 。 = 打 印 当 前 行 号 码 。 # 把 注 释 扩 展 到 下 一 个 换 行 符 以 前 。 以 下 的 是 替 换 标 记 g 表 示 行 内 全 面 替 换 。 p 表 示 打 印 行 。 w 表 示 把 行 写 入 一 个 文 件 。 x 表 示 互 换 模 板 块 中 的 文 本 和 缓 冲 区 中 的 文 本 。 y 表 示 把 一 个 字 符 翻 译 为 另 外 的 字 符 ( 但 是 不 用 于 正 则 表 达 式 ) 4. 选 项 -e command, --expression=command 允 许 多 台 编 辑 。 -h, --help
  • 16. 印 帮 助 , 并 显 示 bug 列 表 的 地 址 。 -n, --quiet, --silent 取 消 默 认 输 出 。 -f, --filer=script-file 引 导 sed 脚 本 文 件 名 。 -V, --version 打 印 版 本 和 版 权 信 息 。 5. 元 字 符 集 ^锚 定 行 的 开 始 如 : /^sed/ 匹 配 所 有 以 sed 开 头 的 行 。 $锚 定 行 的 结 束 如 : /sed$/ 匹 配 所 有 以 sed 结 尾 的 行 。 . 匹 配 一 个 非 换 行 符 的 字 符 如 : /s.d/ 匹 配 s 后 接 一 个 任 意 字 符 , 然 后 是 d 。 * 匹 配 零 或 多 个 字 符 如 : /*sed/ 匹 配 所 有 模 板 是 一 个 或 多 个 空 格 后 紧 跟 sed 的 行 。 [] 匹 配 一 个 指 定 范 围 内 的 字 符 , 如 /[Ss]ed/ 匹 配 sed 和 Sed 。 [^] 匹配一个不在指定范围内的字符,如:/[^A-RT-Z]ed/匹配不包含 A-R 和 T-Z 的一个字母开头,紧 跟 ed 的 行 。 (..) 保 存 匹 配 的 字 符 , 如 s/(love)able/1rs , loveable 被 替 换 成 lovers 。 & 保 存 搜 索 字 符 用 来 替 换 其 他 字 符 , 如 s/love/**&**/ , love 这 成 **love** 。 < 锚 定 单 词 的 开 始 , 如 :/<love/ 匹 配 包 含 以 love 开 头 的 单 词 的 行 。 > 锚 定 单 词 的 结 束 , 如 /love>/ 匹 配 包 含 以 love 结 尾 的 单 词 的 行 。 x{m} 重 复 字 符 x , m 次 , 如 : /0{5}/ 匹 配 包 含 5 个 o 的 行 。 x{m,} 重 复 字 符 x, 至 少 m 次 , 如 : /o{5,}/ 匹 配 至 少 有 5 个 o 的 行 。 x{m,n} 重 复 字 符 x , 至 少 m 次 , 不 多 于 n 次 , 如 : /o{5,10}/ 匹 配 5--10 个 o 的 行 。
  • 17. 6. 实 例 删 除 : d 命 令 $ sed '2d' example----- 删 除 example 文 件 的 第 二 行 。 $ sed '2,$d' example----- 删 除 example 文 件 的 第 二 行 到 末 尾 所 有 行 。 $ sed '$d' example----- 删 除 example 文 件 的 最 后 一 行 。 $ sed '/test/'d example----- 删 除 example 文 件 所 有 包 含 test 的 行 。 替 换 : s 命 令 $ sed 's/test/mytest/g' example-----在整行范围内把 test 替换为 mytest。如果没有 g 标记,则只有 每 行 第 一 个 匹 配 的 test 被 替 换 成 mytest 。 $ sed -n 's/^test/mytest/p' example-----(-n)选项和 p 标志一起使用表示只打印那些发生替换的行。 也 就 是 说 , 如 果 某 一 行 开 头 的 test 被 替 换 成 mytest , 就 打 印 它 。 $ sed 's/^192.168.0.1/&localhost/' example-----&符号表示替换换字符串中被找到的部份。所有以 192.168.0.1 开 头 的 行 都 会 被 替 换 成 它 自 已 加 localhost , 变 成 192.168.0.1localhost 。 $ sed -n 's/(love)able/1rs/p' example-----love 被 标 记 为 1 , 所 有 loveable 会 被 替 换 成 lovers , 而 且 替 换 的 行 会 被 打 印 出 来 。 $ sed 's#10#100#g' example-----不论什么字符,紧跟着 s 命令的都被认为是新的分隔符,所以, “ #” 在 这 里 是 分 隔 符 , 代 替 了 默 认 的 “ /” 分 隔 符 。 表 示 把 所 有 10 替 换 成 100 。 选 定 行 的 范 围 : 逗 号 $ sed -n '/test/,/check/p' example-----所有在模板 test 和 check 所确定的范围内的行都被打印。 $ sed -n '5,/^test/p' example-----打印从第五行开始到第一个包含以 test 开始的行之间的所有行。 $ sed '/test/,/check/s/$/sed test/' example-----对于模板 test 和 west 之间的行,每行的末尾用字 符 串 sed test 替 换 。 多 点 编 辑 : e 命 令 $ sed -e '1,5d' -e 's/test/check/' example-----(-e)选项允许在同一行里执行多条命令。如例子所示 , 第一条命令删除 1 至 5 行,第二条命令用 check 替换 test。命令的执行顺序对结果有影响。如果两个命令 都 是 替 换 命 令 , 那 么 第 一 个 替 换 命 令 将 影 响 第 二 个 替 换 命 令 的 结 果 。
  • 18. $ sed --expression='s/test/check/' --expression='/love/d' example----- 一 个 比 -e 更 好 的 命 令 是 --expression 。 它 能 给 sed 表 达 式 赋 值 。 从 文 件 读 入 : r 命 令 $ sed '/test/r file' example-----file 里的内容被读进来,显示在与 test 匹配的行后面,如果匹配多行, 则 file 的 内 容 将 显 示 在 所 有 匹 配 行 的 下 面 。 写 入 文 件 : w 命 令 $ sed -n '/test/w file' example----- 在 example 中 所 有 包 含 test 的 行 都 被 写 入 file 里 。 追 加 命 令 : a 命 令 $ sed '/^test/a--->this is a example' example<-----'this is a example'被追加到以 test 开头 的 行 后 面 , sed 要 求 命 令 a 后 面 有 一 个 反 斜 杠 。 插 入 : i 命 令 $ sed '/test/i new line -------------------------' example 如 果 test 被 匹 配 , 则 把 反 斜 杠 后 面 的 文 本 插 入 到 匹 配 行 的 前 面 。 下 一 个 : n 命 令 $ sed '/test/{ n; s/aa/bb/; }' example-----如果 test 被匹配,则移动到匹配行的下一行,替换这一 行 的 aa , 变 为 bb , 并 打 印 该 行 , 然 后 继 续 。 变 形 : y 命 令 $ sed '1,10y/abcde/ABCDE/' example-----把 1--10 行内所有 abcde 转变为大写,注意,正则表达 式 元 字 符 不 能 使 用 这 个 命 令 。 退 出 : q 命 令 $ sed '10q' example----- 打 印 完 第 10 行 后 , 退 出 sed 。 保 持 和 获 取 : h 命 令 和 G 命 令
  • 19. $ sed -e '/test/h' -e '$G example-----在 sed 处理文件的时候,每一行都被保存在一个叫模式空间的 临时缓冲区中,除非行被删除或者输出被取消,否则所有被处理的行都将打印在屏幕上。接着模式空间被 清空,并存入新的一行等待处理。在这个例子里,匹配 test 的行被找到后,将存入模式空间,h 命令将其 复制并存入一个称为保持缓存区的特殊缓冲区内。第二条语句的意思是,当到达最后一行后, G 命令取出 保持缓冲区的行,然后把它放回模式空间中,且追加到现在已经存在于模式空间中的行的末尾。在这个例 子 中 就 是 追 加 到 最 后 一 行 。 简 单 来 说 , 任 何 包 含 test 的 行 都 被 复 制 并 追 加 到 该 文 件 的 末 尾 。 保 持 和 互 换 : h 命 令 和 x 命 令 $ sed -e '/test/h' -e '/check/x' example -----互换模式空间和保持缓冲区的内容。也就是把包含 test 与 check 的 行 互 换 。 7. 脚 本 Sed 脚本是一个 sed 的命令清单,启动 Sed 时以-f 选项引导脚本文件名。Sed 对于脚本中输入的命令非 常挑剔,在命令的末尾不能有任何空白或文本,如果在一行中有多个命令,要用分号分隔。以#开头的行 为 注 释 行 , 且 不 能 跨 行 。