sed 用法
sed 工具
-n
p
#打印匹配的第几行,其他的不打印-r
#启用扩展正则表达式,使用该参数可以不用\
去转意-e
#多次匹配,1个内容可能匹配两次,如果两次匹配的内容相同的话sed -n '/root/'Ip test.txt
#忽略大小写sed '1,10d' test.txt
#删除内容sed -i '1,10s/root/test/' test.txt
#把改变的内容写入文件,默认是不改变的,只是把改的打印出来,却不改变文件内容sed '1,10s/root/test/g' test.txt
#替换sed -nr 's/(test01:).*(test01:).*/xx:& yy:&\/'p test.txt
# ‘&’用法是匹配前面’()’内容,而’&’则表示匹配到的行的一整行内容
-n``p
:
[test@xujb01 exmple]$ sed -n '/root/'p 01
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
-e
:
[test@xujb01 exmple]$ sed -n -e '/root/'p -e '/test01/'p 01
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
test01:x:1001:1001::/home/test01:/sbin/nologin
Ip
:
[test@xujb01 exmple]$ sed -n '/bus/'Ip 01
ssssBUS
dbus:x:81:81:System message bus:/:/sbin/nologin
&:
[test@xujb01 exmple]$ sed -rn 's/(test01:).*(test01:).*/\1---\2/'p 01
test01:---test01:
1、 ‘&’匹配到行的一整行内容,
2、 ‘\1’ ‘\2’表示第一个括号的内容和第二个括号的内容
[test@xujb01 exmple]$ sed -rn 's/(test01:).*(test01:).*/XX:\1-&---\2-&/'p 01
XX:test01:-test01:x:1001:1001::/home/test01:/sbin/nologin---test01:-test01:x:1001:1001::/home/test01:/sbin/nologin
4、 所以根据第三条可以匹配‘&’的效果,而且可以指定位置添加内容:
[test@xujb01 exmple]$ sed -rn 's/(test01:)(.*)(test01:)(.*)/xx:\1\2---yy:\3\4/'gp 01
xx:test01:x:1001:1001::/home/---yy:test01:/sbin/nologin
或者
[test@xujb01 exmple]$ sed -rn 's/(test01:.*)(test01:.*)/xx:\1---yy:\2/'gp 01
xx:test01:x:1001:1001::/home/---yy:test01:/sbin/nologin
5、 sed 打印行号
[test@xujb01 exmple]$ sed -n -e '1,3 =' test.txt
1
2
3
-------------------------------------------------------------------
[test@xujb01 exmple]$ sed -n -e '1,3=' -e '1,3'p test.txt
1
root:x:0:0:root:/root:/bin/bash
2
bin:x:1:1:bin:/bin:/sbin/nologin
3
daemon:x:2:2:daemon:/sbin:/sbin/nologin