- 打印某行
打印第二行
MacBook-Pro:develop qiuxuefei$ sed -n '2'p passwd
# User Database
打印所有行
MacBook-Pro:develop qiuxuefei$ sed -n '1,$'p passwd
##
# User Database
#
# Note that this file is consulted directly only when the system is running
备注:截图没有全部截取
打印第一到第二行
MacBook-Pro:develop qiuxuefei$ sed -n '1,2'p passwd
##
# User Database
- 打印包含某个字符串的行
MacBook-Pro:develop qiuxuefei$ sed -n '/NetBIOS/'p passwd
_netbios:*:222:222:NetBIOS:/var/empty:/usr/bin/false
- -e可以实现多个行为
说明:满足两个任意条件的都展现,类似或
MacBook-Pro:develop qiuxuefei$ sed -e '/NetBIOS/'p -e '/captiveagent/'p -n passwd
_netbios:*:222:222:NetBIOS:/var/empty:/usr/bin/false
_captiveagent:*:258:258:captiveagent:/var/empty:/usr/bin/false
- 删除某行或者多行
MacBook-Pro:develop qiuxuefei$ sed '1,3'd passwd
# Note that this file is consulted directly only when the system is running
# in single-user mode. At other times this information is provided by
# Open Directory.
MacBook-Pro:develop qiuxuefei$ more passwd
##
# User Database
#
# Note that this file is consulted directly only when the system is running
- 替换字符或字符串
MacBook-Pro:develop qiuxuefei$ sed 's/Database/ssssssssss/g' passwd
##
# User ssssssssss
#
# Note that this file is consulted directly only when the system is running
# in single-user mode. At other times this information is provided by
# Open Directory.
上例中的 ‘s’ 就是替换的命令, ‘g’ 为本行中全局替换,如果不加 ‘g’ 只换该行中出现的第一个。除了可以使用 ‘/’ 作为分隔符外,还可以使用其他特殊字符例如 ‘#’ 或者 ‘@’ 都没有问题。
数字替换为空
MacBook-Pro:develop qiuxuefei$ sed 's/[0-9]//g' passwd
# Open Directory.
##
nobody:*:-:-:Unprivileged User:/var/empty:/usr/bin/false
字母替换为空
MacBook-Pro:develop qiuxuefei$ sed 's/[a-zA-Z]//g' passwd
# (8)
# .
##
:*:-2:-2: ://:///
:*:0:0: ://://
- 直接修改文件的内容
MacBook-Pro:develop qiuxuefei$ sed -i 's/Database/ssssssss/g' passwd