sed命令基本使用
sed:Stream Editor文本流编辑,sed是一个“非交互式的”面向字符流的编辑器。能同时处理多个文件多行的内容,可以不对原文件改动,把整个文件输入到屏幕,可以把只匹配到模式的内容输入到屏幕上。还可以对原文件改动,但是不会再屏幕上返回结果。
基本语法
sed的命令格式: sed [option] 'sed command'filename
sed的脚本格式: sed [option] -f 'sed script'filename
命令选项
s 表示查找并替换
-i 表示直接修改源文件
-E 支持扩展表达式
-e 表示可以指定表达式
-n :只打印模式匹配的行
-e :直接在命令行模式上进行sed动作编辑,此为默认选项
-f :将sed的动作写在一个文件内,用–f filename 执行filename内的sed动作
-r :支持扩展表达式
-i :直接修改文件内容
x,为行号
x,y 表示行号从x到y
/pattern 查询包含模式的行
/pattern /pattern 查询包含两个模式的行
pattern/,x 在给定行号上查询包含模式的行
x,/pattern/ 通过行号和模式查询匹配的行
x,y! 查询不包含指定行号x和y的行
命令使用
查询使用
[root@xuniji01 ~]# cat b.txt
hello from hogwarts
hello from seyenriby
hello from testerhome
[root@xuniji01 ~]# sed -n '2p' b.txt #只显示第2行,-n只打印匹配的行
hello from seyenriby
[root@xuniji01 ~]# sed -n '1,2p' b.txt #只显示第1-2行
hello from hogwarts
hello from seyenriby
[root@xuniji01 ~]# sed -n '/test/p' b.txt #打印包含test字符的行
hello from testerhome
[root@xuniji01 ~]# sed -n '/hog/,2p' b.txt #打印文件中匹配hog的行到第2行
hello from hogwarts
hello from seyenriby
#即匹配test,也匹配sey,但是是有顺序的
[root@xuniji01 ~]# sed -n '/seye/,/test/p' b.txt
hello from seyenriby
hello from testerhome
[root@xuniji01 ~]# sed -n '/test/,/seye/p' b.txt
hello from testerhome
#打印文件中第一行到第四行的内容,并且带上行号
#当用到sed不同的编辑命令时,用{},且不同命令之间用分号隔开
[root@xuniji01 ~]# sed -n '1,4{=;p}' b.txt
1
hello from hogwarts
2
hello from seyenriby
3
hello from testerhome
#感叹号是取反的意思
[root@xuniji01 ~]# sed -n '1,2!{=;p}' b.txt
3
hello from testerhome
[root@xuniji01 ~]# sed -n '1,2!p' b.txt
hello from testerhome
替换字符
将原文中的testerhome替换为world
[root@xuniji01 ~]# cat b.txt
hello from hogwarts
hello from seyenriby
hello from testerhome
[root@xuniji01 ~]# sed 's#testerhome#world#' b.txt
hello from hogwarts
hello from seyenriby
hello from world
s,代表替换,s后面可以接任何字符
#,代表分割,这里就是用后面的world,替换前面的testerhome
################################分割线##############################################
#将t开头的后面两个字符,一共三个字符替换为xxx
[root@xuniji01 ~]# cat b.txt
hello from hogwarts
hello from seyenriby
hello from testerhome
[root@xuniji01 ~]# sed 's/t../xxx/' b.txt
hello from hogwarts
hello from seyenriby
hello from xxxterhome
#如果是4个xxxx,会把原来的tes三个字符,再补一个x,但是不会破坏后面的terhome
[root@xuniji01 ~]# cat b.txt
hello from hogwarts
hello from seyenriby
hello from testerhome
[root@xuniji01 ~]# sed 's/t../xxxx/' b.txt
hello from hogwarts
hello from seyenriby
hello from xxxxterhome
[root@xuniji01 ~]#
常用的操作
sed '/^ *#/d' kingbase.conf | sed '/^$/d' #过滤掉文件中的注释内容
sed '/^\s*$/d' file.txt #删除空行