sed练习简记

1. 使用多命令选项-e

sed -e ‘command1’ -e ‘command2’ -e ‘command3’

在/etc/passwd文件中搜索root、nobody或mail

[root@sishen ~]# sed -n -e '/^root/ p' -e '/^nobody/ p' -e '/^mail/ p' /etc/passwdroot:x:0:0:root:/root:/bin/bash

mail:x:8:12:mail:/var/spool/mail:/sbin/nologin

nobody:x:99:99:Nobody:/:/sbin/nologin

2. 使用\折行执行多个命令

[root@sishen ~]# sed -n -e '/^root/ p' \

> -e '/^nobody/ p' \

> -e '/^mail/ p' /etc/passwd

root:x:0:0:root:/root:/bin/bash

mail:x:8:12:mail:/var/spool/mail:/sbin/nologin

nobody:x:99:99:Nobody:/:/sbin/nologin

3. 使用{ }把多个命令组合

如果要执行很多sed命令,可以使用{ } 把他们组合起来执行,如:

[root@sishen ~]# sed -n '{ /^root/ p

/^nobody/ p

/^mail/ p

}' /etc/passwd #注意}’与/etc/passwd之间的空格

root:x:0:0:root:/root:/bin/bash

mail:x:8:12:mail:/var/spool/mail:/sbin/nologin

nobody:x:99:99:Nobody:/:/sbin/nologin

sed脚本文件

首先建立测试文件

[root@sishen ~]# vim sedcommand.sed

s/\([^,]*\),\([^,]*\),\(.*\).*/\2,\1, \3/g

s/^.*/<&>/

s/Developer/IT Manager/

s/Manager/Directory/

[root@sishen ~]# sed -f sedcommand.sed employee.txt

<John Doe,101, CEO>

<Jason Smith,102, IT Directory>

<Raj Reddy,103, Sysadmin>

<Anand Ram,104, IT Directory>

<Jane Miller,105, Sales Directory>

<Jane Miller,#106, Sales Directory>

<Jane Miller,#107, Sales Directory>

sed注释

[root@sishen ~]# cat sedcommand.sed

#交换第一列和第二列

s/\([^,]*\),\([^,]*\),\(.*\).*/\2,\1, \3/g

#把整行内容放入<>中

s/^.*/<&>/

#把Developer替换为IT Manager

s/Developer/IT Manager/

#把Manager替换为DIrectory

s/Manager/Directory/

注意:如果sed脚本第一列开始的两个字符是#n的话,sed会自动使用-n选项(即不自动打印模式空间的内容)一般来说,不采用这种方法,尤其是在写脚本时定义执行脚本命令(即#!)时,容易造成混乱,产生错误,通常做法是使用参数”-n”

posted on 2016-11-14 11:56  Lucky_7  阅读(596)  评论(0编辑  收藏  举报

导航