Linux命令之乐--sed

sed是stream edit的缩写,是处理文本非常重要的工具。

常见用法:

1. 替换文本

1.1 替换文本中的第一处符合的样式

    sed 's/pattern/replace_string' file

    或者

    cat file | sed 's/pattern/replace_string'

1.2 替换全局的符合的样式

     sed 's/pattern/replace_string/g' file

1.3 直接修改原文件

      sed -i 's/pattern/replace_string/g' file

1.4 忽略前面N-1的匹配,从N开始替换

      $ echo this this this|sed 's/this/THIS/2g'

          this THIS THIS

1.5  同时替换多个样式,中间用;隔开

      $ echo a b c|sed 's/a/d/g;s/b/e/g;s/c/f/g'

        d e f

2.  删除匹配项

      sed '/pattern/d' file

   常用于删除空白行

      sed '/^$/d' file

3. 已匹配的字符串标记&

    echo hello China|sed 's/China/[&]/g'

    hello [China]

4. 子串标记,匹配给定样式中的一部分

    echo this is dight 7 in a number | sed 's/dight \([0-9]\)/\1/'

    this is 7 in a number

工作中的应用:

给文本中的每一行添加""

     $ sed 's/^/\"&/g;s/$/&\"/g;s/\r//g' file

     "hello"

     "linux"

你可能感兴趣的:(Linux命令之乐--sed)