zoukankan      html  css  js  c++  java
  • sed用法总结

    目录:

        ★ 命令行参数简介
        ★ 首先假设我们有这样一个文本文件 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,不幸的是,这需要用�

    续行符\,

    [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删



    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:\(.*\)$/\1\2/"
    /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个空格,其余制表符替换成一个空格。

    =========================================================

    2、sed选项
       -n    使用安静模式.则只有经过sed特殊处理的哪一行才会被列出来
       -e    传送带(前面执行完传递给后面)
       -f    跟随脚本文件名
       -r    脱意
       -i    直接修改读取文件

    3、sed命令详解
       a     新增, a 的后面可以接字串,而这些字串会在新的一行出现(目前的下一行)~
       c     取代, c 的后面可以接字串,这些字串可以取代 n1,n2 之间的行!
       d     删除,因为是删除啊,所以 d 后面通常不接任何咚咚;
       i      插入, i 的后面可以接字串,而这些字串会在新的一行出现(目前的上一行);
       p     列印,亦即将某个选择的资料印出。通常 p 会与参数 sed -n 一起运作~
       s     取代,通常这个 s 的动作可以搭配正规表示法!例如 1,20s/old/new/g 
       n    读取下一个输入行, 用下一个命令处理新的行

    4、以下是替换标记
      g    表示行内全面替换
      p    表示打印行
      w    表示把行写入一个文件
      x    表示互换模快板中的文本和缓冲区中的文本
      y    表示把一个字符翻译为另外的字符(不用于正则表达式)

    5、元字符集,匹配符
    ^       锚定行的开始. 如/^sed/ 匹配所有以sed开头的行
    $       锚定行的结束. 如/sed$/ 匹配所有以sed结尾的行
    .         匹配一个非换行符. 如/*sed/ 匹配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结尾的单词行
    x\{m\}       重复字符x,m次. 如/o\{5\}匹配包含5个o的行
    x\{m,\}      重复字符x,至少m次. 如 /o\{5,}/匹配至少有5个o的行
    x\{m,n\}    重复字符x,至少m次.把多余n次. 如 /o\{5,10\}/匹配5-10个o的行

    6、sed中查找模式匹配
    .            单字通配符
    [0-9]      匹配0-9
    [^a-z]    不匹配a-z的所有其它字符
    “.*”         匹配””内任何字符串
    ^            匹配行开始
    $            匹配行结束

    7、例子
    删除: dd命令
    sed ‘2d’ file                 删除file文件的第2行
    sed ‘2,$d’ file             删除file文件的第2行到末尾所有行
    sed ‘$d’ file                删除file文件的最后一行
    sed ‘/test/’d file         删除file文件所有包含test的行
    sed d file                   删除file文件中的所有行
    sed 2,5d file              删除file中的2-5行
    sed /abc/d file          删除file中包含字符串abc所有的行

    替换: s命令
    sed ‘s/test/mytest/g’ file        在整行范围内把test替换为mytest. 如果没有g标记,则只有每行第一个匹配的test被替换成mytest
    sed -n ‘s/^test/mytest/p’ file        -n选项和p标志一起使用表示只打印那些发生替换的行, 如果某一行开头的test被替换成mytest,就打印它
    sed ‘s/^192.168.1.1/&localhost’ file    &符号表示替换字符串中被找到的部分. 所有以192.168.1.1开头的行都会被替换成它自己加localhost,变成192.168.1.1localhost
    sed -n ‘s/\(love\)able/\1rs/p’ file    love被标记为1,所有loveable会被替换成lovers,而且替换的行会被打印出来
    sed ‘s#10#100#g’ file            不论什么字符,紧跟着s的命令都被认为是最新的分隔符,所以,’#’在这里是分隔符,代替了默认的”/”分隔符. 表示把所有10替换成100

    选定行的范围: 逗号
    sed -n ‘/test/,/check/p’ file        所有在模块test和check所确定范围内的行都被打印
    sed -n ‘5,/^test/p’ file                 打印从第5行开始到第一个包含以test开始行之间的所有行
    sed ‘/test/,/check/s/$/sed test/’ file    对于模块test和west之间的行,每行的末尾用字符串sed test替换

    多点编辑: e命令
    sed -e ‘1,5d’ -e ‘s/test/check/’ file    -e选项允许在同一行里执行多条命令.删除1-5行,check替换test
    sed -e ‘/and/s/aaa/bbb’ file           sed中用bbb替换同一行中包括字符串and的字符串aaa,而不是每一行中的字符串aaa

    读入文件: r命令
    sed ‘/test/r file_a’ file        file_a里的内容被读进来,显示在与test匹配的行后面. 如果匹配多行,则file_a内容将显示在所有匹配行的下面

    写入文件: w命令
    sed -n ‘test/w file_a’ file        file中所包含的test行都被写入file里

    插入: i命令
    sed ‘/test/i\\ new line’ file        如果test被匹配, 则把反斜杠后面的文本插入到匹配行的上面
    sed -e ‘1 ia’ -e ‘$ a3′ file             在第一行上面插入a,在末尾行下面插入3

    下一个: n命令
    sed ‘/test/{n; s/aa/bb/;}; file        如果test被匹配, 则移动到匹配行的下一行,替换这一行的aa变为bb, 并打印该行,然后继续

    =========================================================
    ★ 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.


    linux sed 批量替换多个文件中的字符串
    比如,要将目录/modules下面所有文件中的zhangsan都修改成lisi,这样做:

    sed -i "s/zhangsan/lisi/g" `grep zhangsan -rl /modules`

    解释一下:

    -i 表示inplace edit,就地修改文件
    -r 表示搜索子目录
    -l 表示输出匹配的文件名


    这个命令组合很强大,要注意备份文件。


    (1)sed 'y/1234567890/ABCDEFGHIJ/' test_sed

    sed 'y/1234567890/ABCDEFGHIJ/' filename
    ABCDEFGHIJ
    BCDEFGHIJA
    CDEFGHIJAB
    DEFGHIJABC
    注意变换关系是按两个list的位置对应变换

    其中:test_sed的内容是:

    1234567890
    2345678901
    3456789012
    4567890123


    (2)
    替换每行所有匹配

    sed 's/01/Ab/g' test_sed
    1234567890
    23456789Ab
    3456789Ab2
    456789Ab23

    注意:第一行的0,1没有分别替换为A,b



    删除: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,并打印该行,然后继续

    =========================================================

    n/N用法说明:
    sed的语法格式:

    sed [option] {sed-command} {input-file}

    sed在正常情况下,将处理的行读入模式空间(pattern space),脚本中的“sed-command(sed命令)”就一条接着一条进行处理,知道脚本执行完毕。然后该行呗输出,模式(pattern space)被清空;接着,在重复执行刚才的动作,文件中的新的一行被读入,直到文件处理完毕。

    但是,由于种种原因,如用户希望在某个条件下,脚本中的某个命令被执行或希望模式空间(pattern space)保留,以便下一次使用,这都有可能使sed在处理文件的时候,不按照正常的流程来进行处理,这时候就需要用sed高级命令来满足需求。

    先来说说命令n和命令N

    命令n:读取下一行到pattern space。由于pattern space中有按照正常流程读取的内容,使用n命令后,pattern space中又有了一行,此时,pattern space中有2行内容,但是先读取的那一行不会被取代、覆盖或删除;当n命令后,还有其他命令p的时候,此时打印出的结果是n命令读取的那一行的内容。

    看下图,你就明白了。

    新建文件,其内容如下

    cat 1.txt

    1

    2

    正常sed流程

    使用n命令后,

    N命令:将下一行添加到pattern space中。将当前读入行和用N命令添加的下一行看成“一行”。

    新建文件1.txt

    cat 1.txt

    1

    2

    正常sed流程

    使用N命令后

    =========================================================
    变形: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对于脚本中输入的命令非常挑剔,在命令的末尾不能有任何空白或文本,如果在一行中有多个命令,要用分号分隔。以#开头的行为注释行,且不能跨行。

    8. 小技巧

    • 在sed的命令行中引用shell变量时要使用双引号,而不是通常所用的单引号。下面是一个根据name变量的内容来删除named.conf文件中zone段的脚本:

      name='zone\ "localhost"'
      sed "/$name/,/};/d" named.conf
    sed -i "s/oldstring/newstring/g" `grep oldstring -rl yourdir`

    例如:替换/home下所有文件中的www.bcak.com.cn为bcak.com.cn

    sed -i "s/www.bcak.com.cn/bcak.com.cn/g" `grep www.bcak.com.cn-rl /home`

    sed调试:sedsed -d -f sedfile

    二、下面这条命令:

    perl -pi -e 's|ABCD|Linux|g' `find ./ -type f`
    将调用perl执行一条替换命令,把find命令找到的所有文件内容中的ABCD替换为Linux

    find ./ -type f
    此命令是显示当前目录下所有的文件

    上面的“s|ABCD|Linux| g”是perl要执行的脚本,即把所有ABCD替换为Linux
    如果不写最后的那个g,“s|ABCD|Linux| ”将只替换每一行开头的ABCD


    当编辑指令(参照[section2.2])在命令列上执行时,其前必须加上选项-e。其命令格式如下:

    sed-e'编辑指令1'-e'编辑指令2'...文件档

    其中,所有编辑指令都紧接在选项-e之後,并置於两个"'"特殊字元间。另外,命令上编辑指令的执行是由

    左而右。

    一般编辑指令不多时,使用者通常直接在命令上执行它们。例如,删除yel.dat内1至10行资料,并将其

    馀文字中的"yellow"字串改成"black"字串。此时,可将编辑指令直接在命令上执行,其命令如下:

    sed-e'1,10d'-e's/yellow/black/g'yel.dat

    在命令中,编辑指令'1,10d'(解[5])执行删除1至10行资料;编辑指令's/yellow/black/g'(解[6]),

    "yellow"字串替换(substuite)成"black"字串。

    2.2sed的编辑指令

    sed编辑指令的格式如下:

    [address1[,address2]]function[argument]

    其中,位址参数address1、address2为行数或regularexpression字串,表示所执行编辑的资料行;函数参

    数function[argument]为sed的内定函数,表示执行的编辑动作。

    下面两小节,将仔细介绍位址参数的表示法与有哪些函数参数供选择。

    2.2.1位址(address)参数的表示法

    实际上,位址参数表示法只是将要编辑的资料行,用它们的行数或其中的字串来代替表示它们。下面举几个例子

    说明(指令都以函数参数d(参照[section4.2])为例):

    删除档内第10行资料,则指令为10d。

    删除含有"man"字串的资料行时,则指令为/man/d。

    删除档内第10行到第200行资料,则指令为10,200d。

    删除档内第10行到含"man"字串的资料行,则指令为10,/man/d。

    接下来,以位址参数的内容与其个数两点,完整说明指令中位址参数的表示法(同样也以函数参数d为例)。

    位址参数的内容:

    位址为十进位数字:此数字表示行数。当指令执行时,将对符合此行数的资料执行函数参数指示的编辑动作。例如,

    删除资料档中的第15行资料,则指令为15d(参照[section4.2])。其馀类推,如删除资料档中的第m行资料,则

    指令为md。

    位址为regularexpression(参照[附录A]):

    当资料行中有符合regularexpression所表示的字串时,则执行函数参数指示的编辑动作。另外,在

    regularexpression前後必须加上"/"。例如指令为/t.*t/d,表示删除所有含两"t"字母的资料行。其中,"."

    表示任意字元;"*"表示其前字元可重任意次,它们结合".*"表示两"t"字母间的任意字串。

    位址参数的个数:在指令中,当没有位址参数时,表示全部资料行执行函数参数所指示的编辑动作;当只有一位址

    参数时,表示只有符合位址的资料行才编辑;当有两个位址参数,如address1,address2时,表示对资料区执行

    编辑,address1代表起始资料行,address2代表结束资料行。对於上述内容,以下面例子做具说明。

    例如指令为

    d

    其表示删除档内所有资料行。

    例如指令为

    5d

    其表示删除档内第五行资料。

    例如指令为

    1,/apple/d

    其表示删除资料区,由档内第一行至内有"apple"字串的资料行。

    例如指令为

    /apple/,/orange/d

    其表示删除资料区,由档内含有"apple"字串至含有"orange"字串的资料行

    2.2.2有那些函数(function)参数

    下页表中介绍所有sed的函数参数(参照[chapter4])的功能。

    函数参数功能

    :label建立scriptfile内指令互相参考的位置。
     
     
  • 相关阅读:
    机器学习性能指标精确率、召回率、F1值、ROC、PRC与AUC--周振洋
    机器学习项目实战(一)垃圾邮件的过滤技术-周振洋
    Python音频处理(一)音频基础知识-周振洋
    LightGBM详细用法--机器学习算法--周振洋
    LightGBM的算法介绍
    Oracle数据库学习一 (Oracle数据库安装/环境变量配置/客户端/基础/问题...),待续...
    WebService小白学习 之 Spring整合CXF,添加拦截器 (7)
    WebService小白学习 之 CXF添加拦截器,自定义拦截器 (6)
    WebService小白学习 之 处理一些Map等复杂类型 (5)
    WebService小白学习 之 处理JavaBean以及复合类型,list (4)
  • 原文地址:https://www.cnblogs.com/276815076/p/2204884.html
Copyright © 2011-2022 走看看