zoukankan      html  css  js  c++  java
  • Linux sed 命令实例

    测试文档:

    # cat test.txt
    This is line number 1.
    This is line number 2.
    This is line number 3.
    This is line number 4.
    

      

    sed s 替换文本命令:

    将每一列中第2个 test 替换为 trial

    # sed 's/test/trial/2' test.txt
    

    将每一列中第所有 test 替换为 trial

    # sed 's/test/trial/g' test.txt
    

    只显示被替换的行(-n p):

    # sed -n 's/test/trial/p' test.txt
    

    将替换过结果保存到文件中(w):

    # sed 's/test/trial/w test2.txt' test.txt
    

    将路径中斜线进行转义():

    # sed 's//bin/bash//bin/csh/' /etc/passwd
    

    sed d 删除文本命令:

    删除文本中的所有内容:

    # sed 'd' test.txt
    

    删除文本中第2,3行内容:

    # sed '2,3d' test.txt
    

    删除第1至第3行之前内容:

    # sed '/1/,/3/d' test.txt
    

    删除第3行至尾部的内容:

    # sed '3,$d' test.txt
    

    sed i 插入内容

    在文本第3行之前插入内容:

    # sed '3i this is an inserted line.' test.txt
    

    sed a 添加内容

    在文本第3行之后增加内容:

    # sed '3a this is an appended line.' test.txt
    

    在文本第一行之后增加2行内容:

    # sed '1a this is one line of new test.
    > this is another line of new text.' test.txt
    

    sed c 替换指定的文本内容

    替换第3行文本的内容:

    # sed '3c this is a changed line of text.' test.txt
    

    替换含有指定字符所在行的内容:

    # sed '/number 3/c this is a changed line of text.' test.txt
    

    sed y 按顺序替换对应文本内容:

    替换文本中对应的内容

    # sed 'y/123/789/' test.txt
    

    替换输入中出现的内容:

    # echo "this 1 is a test of 1 try." | sed 'y/123/456/'
    

    sed p 打印输出指定行的内容:

    输出指定行的文本内容:

    # sed -n '/number 3/p' test.txt
    

    打印命令与替换命令混合使用:

    # sed -n '/number 3/{
    p
    s/line/test/p
    }' test.txt
    

    sed w 将一个文本文件按筛选内容写入另个文本文件

    将文件中第1,2行内容写入新文件中。

    # sed '1,2w test2.txt' test.txt
    

    将文本中第1,2行内容写入新文件中。

    # sed -n '/number 3/w test2.txt' test.txt
    

    sed r 将一个文本文件内容写入另个文件文本之后

    将 test2.txt 文件内容插入到 test.txt指定行之后

    # sed '3r test2.txt' test.txt
    

    将 test2.txt 文件内容插入到 test.txt最后一行之后

    # sed '$r test2.txt' test.txt
    

    sed q 执行完特定命令之后就退出

    显示文本第2行之后就退出

    # sed '2q' test.txt
    

    显示替换结果之后就退出:

    # sed '/number 1/{s/number 1/number 0/;q;}' test.txt
    

      

    [THE END]

  • 相关阅读:
    java多线程基础(一)
    重构总体思路
    【Gearman学习笔记】分布式处理入门
    virtualbox安装提示出现严重错误解决办法
    驱动程序vmci.sys版本不正确。请尝试重新安装 VMware
    Gearman任务分布系统部署windows平台_使用Cygwin
    Fatal error: Class 'GearmanClient' not found解决方法
    header('Content-type:text/html;charset = utf-8');出现中文乱码
    heredoc和nowdoc的区别
    SELECT INTO 和 INSERT INTO SELECT 两种表复制语句
  • 原文地址:https://www.cnblogs.com/configure/p/14972863.html
Copyright © 2011-2022 走看看