sed定义
The sed stream editor is a text editor that performs editing operations on information coming from standard input or a file. Sed edits line-by-line and in a non-interactive way.
sed语法
sed [options] ‘addresscommands' [file-to-edit]
1. 1,100:1到100行
$:最后一行
$-1: 倒数第2行
2. /regexp/
/^root/
3. /pattern1/,/parttern2/
第一次被pattern1匹配到的行开始到第一次被pattern2匹配到的行结束
4. 精确匹配到某行
5. startline, +N
从startline 开始,向后的N行
command:
d: delete 符合条件的行
p: 显示符合条件的行
r: 将指定的文件内容添加至符合条件的行处
w: 将指定范围内的内容另存至指定的文件中
s: 查找并替换 默认替换每行中第一个被pattern匹配的字符串
-g修饰符
-i忽略大小写
反向引用
\(\) \1 \2
&:引用前面模式匹配的字符串
[option]
-n: 静默模式 (不显示模式空间的内容)
-p:
-a: a \string:在指定的行后边追加新行
-i: 直接修改原文件
-e: 同时执行多个脚本
-f: /path/sedscript
-r:使用扩展正则表达式
实验:
sed '/^\//a \hello world' /etc/fstab #此文件以'/'开头 后边追加 hello world
sed '/^\//a \hello world\nhello linux' /etc/fstab
#此文件以'/'开头 后边追加 hello world hello linux
sed '/^\//i \hello world\nhello linux' /etc/fstab
#此文件以'/'开头 插入 hello world hello linux
sed '2r/etc/issue' '/etc/fstab'
#在fstab文件的第2行 加issue文件的内容
sed '$r/etc/issue' '/etc/fstab' #在fstab文件的后边追加issue的内容
sed '/pfs/w /tmp/oot.txt' /etc/fstab #在fstab文件中包含pfs字符的行 定向到oot.txt文件中
sed 's/pts/PTS/' /etc/fstab#在fstab文件中把pfs的行都换成大写PFS
sed 's/^\//#/' /etc/fstab #在fstab文件中以'/'开头的都换成#号
sed 's#l..e#&r#g' sed.txt #在sed.txt文件中以l..e的字符串 后项引用加r字符
sed '1,2d' /etc/fstab #删除fstab中的前2行
sed '1 ,+2d' /etc/fstab #删除fstab中的前3行
sed '/sfs/d' /etc/fstab #删除fstab中的包含sfs的行
sed '/^\//d' /etc/fstab #删除fstab中的以'/'开头的行
转载于:https://blog.51cto.com/xiaoxiaoniao/1396159