sed 正则表达式

  • 打印某行

打印第二行

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

转载于:https://my.oschina.net/u/3771523/blog/1634257

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值