1.概述
文本三剑客,grep、sed、awk。今天就简单记录sed命令。
sed stream editor 流编辑器
sed 是行编辑器,按行编辑。区别nona,vi(全屏编辑器)
2.sed模式空间
默认不编辑原文件 仅处理模式空间的数据处理,结束后将模式空间中的内容打印至屏幕
3.语法
sed [OPTION]… {script-only-if-no-other-script} [input-file]…
- [OPTION] 选项,可以多个选项叠加
- {script-only-if-no-other-script} ‘AddressCommand’ 位置+命令的script,单引号’’
- [input-file] 文件,可以多个文件
- -n 静默模式 不在显示模式空间中的内容
- -i 直接修改源文件
- -e script -e script 可以同时执行多个脚本(‘AddressCommand’)
- -f script-file script 可以写成脚本文件后运行
- -r 使用扩展的正则表达式
- 1.startLine,Endline
1,100 第1行到第100行
$ 最后一行 - 2./RegExp/
/^root/ 表示匹配到 行首以root开头的行 - 3./RegExp1/,/RegExp2/
第一次被模式1 匹配到的行开始到模式2匹配到的行结束
当然也可以 /RegExp1/,$ 第一次被模式1匹配到的行到文件尾 - 4.LineNumber
指定行 - 5.StartLinne, +N
从指定行开始,向后N行 总共n+1 行
- d:删除符合条件的行
- p:显示符合条件的行 ,常配合-n 选项 静默模式
- a “string”: 在指定的行后面追加新行,内容为string
- r FILE:将指定的文件与内容添加到符合条件的行处
- w FILE 将指定范围内的内容保存至指定的文件
- s/Pattern/string/ 查找并替换 只替换每一行中第一次被模式匹配到的串
以上命令一般 s/Pattern/string/ 命令 使用较多; a "string" 个人认为也有使用场景
举个栗子
/etc/fdtab 文件内容
etc$cat /etc/fstab
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if