【Linux】sed笔记

sed - stream editor for filtering and transforming text(用于过滤和转换文本的SED流编辑器),主要是以行为单位进行处理,可以将数据行进行替换、删除、新增、选取等特定工作.
语法

sed [-hnV][-e<script>][-f<script文件>][文本文件]

选项:

-n, --quiet, --silent
    suppress automatic printing of pattern space
-e script, --expression=script
    add the script to the commands to be executed
-f script-file, --file=script-file
     add the contents of script-file to the commands to be executed

命令:

c :取代, c 的后面可以接字串,这些字串可以取代 n1,n2 之间的行!
s :取代,可以直接进行取代的工作哩!通常这个 s 的动作可以搭配正规表示法!例如 1,20s/old/new/g 就是啦!
a :新增, a 的后面可以接字串,而这些字串会在新的一行出现(目前的下一行)~
i :插入, i 的后面可以接字串,而这些字串会在新的一行出现(目前的上一行);
d :删除,因为是删除啊,所以 d 后面通常不接任何咚咚;
p :打印,亦即将某个选择的数据印出。通常 p 会与参数 sed -n 一起运行~

实例
①以行为单位的替换(注意:sed 后面接的动作,请务必以 '' 两个单引号括住喔!

yunduo@yunduo-ThinkCentre-XXXX:~/test$ nl abc
     1  a
     2  b
     3  c
     4  d
     5  e
yunduo@yunduo-ThinkCentre-XXXX:~/test$ nl abc | sed '2,5c replace No 2-5 line'
     1  a
replace No 2-5 line

②数据的搜寻并替换

sed 's/要被取代的字串/新的字串/g'

yunduo@yunduo-ThinkCentre-XXXX:~/test$ sed 's/a/1/g' ./abc
1
b
c
d
e

③在第三行后添加一行数据"newline"

yunduo@yunduo-ThinkCentre-XXXX:~/test$ cat testfile 
sudo find ./ -perm 755 | xargs -i cp {} /usr/bin/

sudo docker rm `docker ps -a|grep Exited|awk '{print $1}'`
yunduo@yunduo-ThinkCentre-XXXX:~/test$ sed -e 3a\newline testfile 
sudo find ./ -perm 755 | xargs -i cp {} /usr/bin/

sudo docker rm `docker ps -a|grep Exited|awk '{print $1}'`
newline

④在第二行前插入数据"drink tea"

yunduo@yunduo-ThinkCentre-XXXX:~/test$ sed '2i drink tea' testfile 
sudo find ./ -perm 755 | xargs -i cp {} /usr/bin/
drink tea

sudo docker rm `docker ps -a|grep Exited|awk '{print $1}'`

⑤以行为单位的显示

yunduo@yunduo-ThinkCentre-XXXX:~/test$ nl abc | sed -n '3,5p'
     3  c
     4  d
     5  e

⑥数据的搜寻与显示

yunduo@yunduo-ThinkCentre-XXXX:~/test$ nl abc | sed '/b/p'
     1  a
     2  b
     2  b
     3  c
     4  d
     5  e

⑦以行为单位的删除

yunduo@yunduo-ThinkCentre-XXXX:~/test$ cat abc
a
b
c
d
e
yunduo@yunduo-ThinkCentre-XXXX:~/test$ sed '2,4d' abc
a
e

⑧仅显示处理结果

yunduo@yunduo-ThinkCentre-XXXX:~/test$ sed '/b/p' abc
a
b
b
c
d
e
yunduo@yunduo-ThinkCentre-XXXX:~/test$ sed -n '/b/p' abc
b

⑨多点编辑

yunduo@yunduo-ThinkCentre-XXXX:~/test$ sed -e '3,$d' -e 's/sudo//' testfile 
 find ./ -perm 755 | xargs -i cp {} /usr/bin/

猜你喜欢

转载自www.cnblogs.com/wucaiyun1/p/11208509.html
今日推荐