sed
先复制修改内容:\cp /etc/passwd passwd_cp
-n 打印匹配的行(p:打印):sed -n 'p' /etc/passwd
-i 直接修改文件:sed -ri '/9{3}/ a xxx xxx' passwd_cp(-a:之后添加)
-r 拓展正则:sed -nr '/0{3}/ p' /etc/passwd
-f 加载存放动作的文件
pattern:
匹配第4行:sed -n '4p' /etc/passwd
匹配3-11行:sed -n '3,11 p' /etc/passwd
匹配00的行:sed -n '/00/ p' /etc/passwd
匹配开头到结尾的行:sed -n '/^xiang01/,/xiang03/p' /etc/passwd
xiang01:x:1006:1009::/home/xiang01:/bin/sh
xiang02:x:1007:1010::/home/xiang02:/bin/sh
xiang03:x:1008:1011::/home/xiang03:/bin/sh
匹配51到最后一行:sed -n '51,$ p' /etc/passwd
/bin/sh的行:sed -n '/\/bin\/sh/ p' /etc/passwd
yang2:x:1001:1001::/home/yang2:/bin/sh
yang04:x:1002:1005::/home/yang04:/bin/sh
-i -a:匹配行后添加:sed -ri '/9{3}/ a xxx xxx' passwd_cp
i: 匹配行前添加:sed -i '/xiang01/,/xiang03/ i xxxx xxxx' passwd_cp
u2:x:1004:1007::/home/u2:/bin/sh
u3:x:1005:1008::/home/u3:/bin/sh
xxxx xxxx
xiang01:x:1006:1009::/home/xiang01:/bin/sh
xxxx xxxx
xiang02:x:1007:1010::/home/xiang02:/bin/sh
xxxx xxxx
xiang03:x:1008:1011::/home/xiang03:/bin/sh
r: 从文件中读取内容 再将内容添加到文别的文件:sed -i '/root/ r one.txt' passwd_cp
root@yang01-virtual-machine:/home/yang01/桌面/shell# cat passwd_cp
root:x:0:0:root:/root:/bin/bash
add root content
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
w:将文件配到的内容写入另一个文件 sed -i '/root/ w two.txt' passwd_cp
root@yang01-virtual-machine:/home/yang01/桌面/shell# cat two.txt
root:x:0:0:root:/root:/bin/bash
add root content
d:删除 sed -i '/root/ d' passwd_cp
s替换:
s/old/new
s/old/new/g:sed -i 's/bin/BIN/g' passwd_cp
s/old/new/ig
c 修改:sed -i '/root/ c xxx xxx' passwd_cp
练习一:将1-10行的/bin/bash转换成大写
1):sed -i 's/\/bin\/bash/\/BIN\/BASH/g' passwd_cp
2):不用转义:sed -i '1,10 s#/bin/bash#/BIN/BASH#' passwd_cp
root@yang01-virtual-machine:/home/yang01/桌面/shell# cat passwd_cp
root:x:0:0:root:/root:/BIN/BASH
练习二:
c 修改:sed -i '/root/ c xxx xxx' passwd_cp
root@yang01-virtual-machine:/home/yang01/桌面/shell# cat passwd_cp
xxx xxx
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin