Linux sed 命令是利用脚本来处理文本文件。
sed 可依照脚本的指令来处理、编辑文本文件。
Sed 主要用来自动编辑一个或多个文件、简化对文件的反复操作、编写转换程序等。
sed [-hnV][-e<script>][-f<script文件>][文本文件]
参数说明:
动作说明:
注:a c i 插入多行时,除最后 一行外,每行末尾需要用“\”代表数据未完结。
对 sed 命令大家要注意,sed 所做的修改并不会直接改变文件的内容(如果是用管道符接收的命令的输出,这种情况连文件都没有),而是把修改结果只显示到屏幕上,除非使用“-i”选项才会直接修改文件。
1.查看指定行
[root@iZ1la3d1xbmukrZ ~]# cat student.txt ID Name PHP Linux MySQL Average 1 Lm 82 95 86 87.66 2 Sc 74 96 87 85.66 3 Tg 99 83 93 91.66 [root@iZ1la3d1xbmukrZ ~]# sed -n ‘2p‘ student.txt 1 Lm 82 95 86 87.66 [root@iZ1la3d1xbmukrZ ~]#
2.删除2-4行(对本身文件不修改)
[root@iZ1la3d1xbmukrZ ~]# sed ‘2,4d‘ student.txt ID Name PHP Linux MySQL Average [root@iZ1la3d1xbmukrZ ~]# cat student.txt ID Name PHP Linux MySQL Average 1 Lm 82 95 86 87.66 2 Sc 74 96 87 85.66 3 Tg 99 83 93 91.66 [root@iZ1la3d1xbmukrZ ~]#
3.添加数据
[root@iZ1la3d1xbmukrZ ~]# sed 2a\hello student.txt ID Name PHP Linux MySQL Average 1 Lm 82 95 86 87.66 hello 2 Sc 74 96 87 85.66 3 Tg 99 83 93 91.66 [root@iZ1la3d1xbmukrZ ~]# sed ‘2i hello \ > world‘ student.txt ID Name PHP Linux MySQL Average hello world 1 Lm 82 95 86 87.66 2 Sc 74 96 87 85.66 3 Tg 99 83 93 91.66
4.替换数据
[root@iZ1la3d1xbmukrZ ~]# cat student.txt | sed ‘2c No such person\ No such person ‘ ID Name PHP Linux MySQL Average No such person No such person 2 Sc 74 96 87 85.66 3 Tg 99 83 93 91.66 [root@iZ1la3d1xbmukrZ ~]#
5 字符串替换
“c”动作是进行整行替换的,如果仅仅想替换行中的部分数据,就要使用“s”动作了。s 动作的格式是:
[root@localhost ~]# sed ‘s/旧字串/新字串/g’ 文件名
直接进行简单替换
[root@iZ1la3d1xbmukrZ ~]# sed ‘s/74/99/g‘ student.txt ID Name PHP Linux MySQL Average 1 Lm 82 95 86 87.66 2 Sc 99 96 87 85.66 3 Tg 99 83 93 91.66 [root@iZ1la3d1xbmukrZ ~]#
正则进行替换
[root@iZ1la3d1xbmukrZ ~]# cat student.txt ID Name PHP Linux MySQL Average 1 Lm 82 95 86 87.66 2 Sc 74 96 87 85.66 3 Tg 99 83 93 91.66 [root@iZ1la3d1xbmukrZ ~]# sed ‘4s/^/#/g‘ student.txt ID Name PHP Linux MySQL Average 1 Lm 82 95 86 87.66 2 Sc 74 96 87 85.66 #3 Tg 99 83 93 91.66 [root@iZ1la3d1xbmukrZ ~]#
执行多个替换
[root@iZ1la3d1xbmukrZ ~]# sed -e ‘s/Lm//g ; s/Tg//g‘ student.txt ID Name PHP Linux MySQL Average 1 82 95 86 87.66 2 Sc 74 96 87 85.66 3 99 83 93 91.66 [root@iZ1la3d1xbmukrZ ~]# sed -e ‘s/Lm//g > s/Tg//g‘ student.txt ID Name PHP Linux MySQL Average 1 82 95 86 87.66 2 Sc 74 96 87 85.66 3 99 83 93 91.66 [root@iZ1la3d1xbmukrZ ~]#
“-e”选项可以同时执行多个 sed 动作,当然如果只是执行一个动作也可以使用“-e”选项,但是这时没有什么意义。还要注意,多个动作之间要用“;”号或回车分割。
原文:https://www.cnblogs.com/dalianpai/p/12694864.html