sed 命令---常用方式

1. 两种语法:

  a. 直接操作:sed +选项  ‘指令' 文件;

  b. 命令文件调用(文件中写好sed指令):sed   +选项  -f  包含sed指令的文件  文件。

2. 选项及命令解释:

  常用选项:  

    -r:使用扩展正则表达式

    -e:它告诉sed将下一个参数解释为一个sed指令,只有当命令行上给出多个sed指令时才需要使用-e选项

    -f:后跟保存了sed指令的文件

    -i:直接对内容进行修改,不加-i时默认只是预览,不会对文件做实际修改

    -n:取消默认输出,sed默认会输出所有文本内容,使用-n参数后只显示处理过的行

  常用命令:   

    a:追加  向匹配行后面插入内容

    c:更改  更改匹配行的内容

    i:插入  向匹配行前插入内容

    d:删除  删除匹配的内容

    s:替换  替换掉匹配的内容

    p:打印  打印出匹配的内容,通常与-n选项和用

3.实际操作:

  1)在第一行后面,追加一行(在命令a前面加行数:a,2a 为第一行后面追加,第二行后面追加):

[root@localhost home]# cat 1.txt
123
[root@localhost home]# sed -i 'ahello' 1.txt
[root@localhost home]# cat 1.txt
123
hello

 扩展:#向内容123后面添加hello(命令:sed -i '/123/ahello' 1.txt)

  2)在第二行位置,插入:

[root@localhost home]# cat 1.txt
hello
123
[root@localhost home]# sed -i '2i456' 1.txt
[root@localhost home]# cat 1.txt
hello
456
123
[root@localhost home]# 

  扩展:在包含123的行之前插入hello(命令:sed -i '/123/ihello' 1.txt)

  3)行替换:替换第三内容为hello

[root@localhost home]# cat 1.txt
hello
456
123
[root@localhost home]# sed -i '3chello' 1.txt
[root@localhost home]# cat 1.txt
hello
456
hello
[root@localhost home]# 

  扩展:在包含123的行替换为hello(命令:sed -i '/123/chello' 1.txt)

  4)字符串替换:只将每一行匹配的第一个lo替换为p

[root@localhost home]# cat 1.txt
hello
456
hello
[root@localhost home]# sed -i 's/lo/p/' 1.txt
[root@localhost home]# cat 1.txt
help
456
help

  扩展:将所有lo替换为p(命令:sed -i 's/lo/p/g' 1.txt)、将每行第二个匹配到的lo替换为p(命令:sed -i 's/lo/p/2' 1.txt)

  5) 删除行:删除

[root@localhost home]# cat 1.txt
help
456
help
[root@localhost home]# sed '3d' 1.txt
help
456
[root@localhost home]#

  扩展:删除匹配到123的行(命令:sed -i '/123/d' 1.txt)

引用来源:shell脚本--sed的用法详解_linux shell_脚本之家 (jb51.net)

posted on 2021-10-28 14:10  呆呆人  阅读(330)  评论(0)    收藏  举报