发布时间:2026-06-18阅读(1)
Linux中的命令主要是操作文件或字符串,对字符串进行匹配、修改、替换是非常常见的操作。sed作为Shell三剑客之一,对文件中的字符串处理尤其擅长,不仅可以将修改后的结果在标准输出显示,还可以直接替换修改原始文件。


sed [-nefri] command 输入文本
常用选项:
-e进行多项编辑,即对输入行应用多条sed命令时使用-n取消默认的输出-f指定sed脚本的文件名-r 使用扩展正则表达式-i inplace,原地编辑(修改源文件)
命令选项:
p 打印匹配行 = 显示文件行号 a/ 在定位行号后附加新文本信息 i/ 在定位行号后插入新文本信息 d 删除定位行 c/ 用新文本替换定位文本s 使用替换模式替换相应模式r 从另一个文本中读文本w 写文本到一个文件
sed -n 1,5p input.txt 打印1-5行sed -n $p input.txt 打印最后一行sed -n /root/p input.txt 打印包括root的整行sed 1,5d input.txt 删除1-5行sed /root/d input.txt 删除包括root的行
!取反所选行:
hioier@yunpc:~/scripts$ sed -n 1,3!p input.txtdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinbin:x:2:2:bin:/bin:/usr/sbin/nologinnews:x:9:9:news:/var/spool/news:/usr/sbin/nologin

行首添加注释

行首行尾同时替换:
sed -n 1,3s/^/# &/g;1,3s/$/& >>/gp input.txt
i\在当前行之前插入文本。多行时除最后一行外,每行末尾需用"\"续行 a\在当前行后添加一行或多行。多行时除最后一行外,每行末尾需用“\”续行 c\用此符号后的新文本替换当前行中的文本。多行时除最后一行外,每行末尾需用"\"续行,整行替换
hioier@yunpc:~/scripts$ sed /root/a\hioier.com input.txtroot:x:0:0:root:/root:/bin/bashhioier.comroot:x:0:0:root:/root:/bin/bashhioier.comroot:x:0:0:root:/root:/bin/bashhioier.comdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinbin:x:2:2:bin:/bin:/usr/sbin/nologinnews:x:9:9:news:/var/spool/news:/usr/sbin/nologinhioier@yunpc:~/scripts$ sed /root/a\hioier.com\nhello cat. input.txtroot:x:0:0:root:/root:/bin/bashhioier.comhello cat.root:x:0:0:root:/root:/bin/bashhioier.comhello cat.root:x:0:0:root:/root:/bin/bashhioier.comhello cat.
hioier@yunpc:~/scripts$ sed /root/c\hioier.com\> hello cat.> input.txthioier.comhello cat.hioier.comhello cat.hioier.comhello cat.daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinbin:x:2:2:bin:/bin:/usr/sbin/nologinnews:x:9:9:news:/var/spool/news:/usr/sbin/nologin
hioier@yunpc:~/scripts$ sed 2r test.txt input.txtroot:x:0:0:root:/root:/bin/bashroot:x:0:0:root:/root:/bin/bashhioier.com 1hioier.com 2hioier.com 3root:x:0:0:root:/root:/bin/bashdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinbin:x:2:2:bin:/bin:/usr/sbin/nologinnews:x:9:9:news:/var/spool/news:/usr/sbin/nologin
hioier@yunpc:~/scripts$ sed /root/w output.txt input.txtroot:x:0:0:root:/root:/bin/bashroot:x:0:0:root:/root:/bin/bashroot:x:0:0:root:/root:/bin/bashdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinbin:x:2:2:bin:/bin:/usr/sbin/nologinnews:x:9:9:news:/var/spool/news:/usr/sbin/nologinhioier@yunpc:~/scripts$ cat output.txtroot:x:0:0:root:/root:/bin/bashroot:x:0:0:root:/root:/bin/bashroot:x:0:0:root:/root:/bin/bash
hioier@yunpc:~/scripts$ sed -n /root/= input.txt123hioier@yunpc:~/scripts$ sed -ne /root/= -ne /root/p input.txt1root:x:0:0:root:/root:/bin/bash2root:x:0:0:root:/root:/bin/bash3root:x:0:0:root:/root:/bin/bashhioier@yunpc:~/scripts$
sed脚本就是将多个操作命令放到一个文件中执行。
过滤.bashrc配置文件:
sed /^#/d;/^$/d;/^\t$/d;/^\t#/d;/^.*#/d bashrc
在文件收尾添加信息:
sed 1i\------ start ------ bashrcsed $a\------ end ------ bashrc
sed.sh
#!/bin/sed -fs/root/hioier/g1i\------- start ------$a\------- end ------
sed -f sed.sh input.txt./sed.sh -i input.txt
Copyright © 2024 有趣生活 All Rights Reserve吉ICP备19000289号-5 TXT地图HTML地图XML地图