zoukankan      html  css  js  c++  java
  • sed 入门

         sed 是 stream editor(流编辑器)的缩写。它能够完美配合正则表达式使用。sed命令众所周知的一个功能是文本的替换。

    1、 sed可以替换给定文本中的字符串。它可以配合正则表达式来进行匹配
         $ sed  ' s/pattern/replace_string/ '  file
         或者
         $ cat file | sed sed  ' s/pattern/replace_string/ '  //这个命令从stdin中读取输入
         使用 -i 选项可以将替换结果应用于源文件。一般在进行替换后利用重定向来保存文件。
         $ sed  ' s/pattern/replace_string/ '  file > newfile
         用新文件来替换源文件:$ mv newfile file

         也可以用一行命令来完成: 
         $ sed  -i  ' s/pattern/replace_string/ '  file

         sed  ' s/pattern/replace_string/ '  file 可以将每行中第一处匹配样式的内容替换掉,要想把所有符合的字符都替换掉,需要在命令尾部加上参数 g,如下
         sed  ' s/pattern/replace_string/ g '  file 
         后缀/g表示sed会替换每一处匹配。

         当不需要每处替换时,可以选用/Ng来选择从第N处开始替换,如下:
         sed  ' s/pattern/replace_string/Ng'  file
         $ echo hello hello hellohello | sed 's/hello/HELLO/2g'
         $ hello HELLO HELLOHELLO   // 输出结果

         字符/ 在sed中起到定界符作用,我们也可选用任意定界符
         sed  ' s:pattern:replace_string:g '
         sed  '   s|pattern|replace_string|g'

         当定界符出现在要匹配的样式中时则需要用前缀 来对其转义:
         sed  ' s; he;llo;replace_string; '

    2、 sed 命令包含多个可用于对文本处理的选项。将这些选项已合理的顺序组合,可以在一行命令中解决很多复杂的问题。如下:

          a、移除空白行:
         空白行可用'^$'进行匹配
         $ sed '/^$/d' file
         
           b、已匹配字符串标记(&)
         在sed中,用&标记匹配样式的字符串,就能够在替换字符串时使用已匹配的内容。
         $ echo this is an example | sed 's/w=/[&]/g'
         $ [this] [is] [an] [example]

         ps: w为 正则表达式匹配字符(Perl风格的正则表达式),但是下表中的字符并不是所有的工具都支持
         
         利用正则表达式w+匹配一个单词,然后用 [ & ] 替换它。&对应于之前所匹配到的单词。
         
           c、子串匹配标记 1
         &代表匹配给定样式的字符串。我们也可以匹配给定样式中的其中一部分。
         $ echo this is digit 7 in a number | sed ' s/digit ([0-9])/1/'
         $ this is 7 in a number
         上述命令将digit 7 替换为7。样式中匹配到的子串是7.
         $ echo seven EIGHT | sed 's/([a-z]+) ([a-z]+)/2 1/'
         $ EIGHT seven
         ([a-z]+) 匹配第一个单词,([a-z]+) 匹配第二个单词。 1和 2用来引用它们。这种引用被称为后向引用。 在替换部分,它们的次序被更改为2 1,因此结果就呈现出逆序的形式。

          d、组合多个表达式
         利用管道组合多个sed命令。
         $ sed 'expression' | sed 'expression1'
         等价于: 
         $ sed 'expression; expression1'
         
           e、引用
         sed表达式通常用单引号来引用。不过也可以使用双引号。双引号会通过对表达式求值来对其进行扩展。
         如:
         $ text=hello
         $ echo hello world | sed "s/$text/HELLO/"
         $ HELLO world
         $text 求值的结果是hello
         
         

  • 相关阅读:
    maven常用仓库
    AD域安装及必要设置
    oracle创建表空间
    javascript弹出模态窗体
    win8.1 AMD 屏幕亮度无法调整
    tomcat优化
    CentOS 6.2 中文
    tomcat之JNDI数据源配置
    eclipse中tomcat配置(待完善)
    Ant打jar包指定MainClass
  • 原文地址:https://www.cnblogs.com/jiangu66/p/3221697.html
Copyright © 2011-2022 走看看