操作图三剑客全部学完后补充
1. grep
Global search regular expression and print out the line
全面搜索研究正则表达式并显示出来
grep 命令是一种强大的文本搜索工具 , 根据用户指定的“模
式”对目标文本进行匹配检查 , 打印匹配到的行
由正则表达式或者字符及基本文本字符所编写的过滤条件
grep 的格式
grep 匹配条件 处理文件
例如
grep root passwd
grep ^root passwd
grep root$ passwd
grep -i root passwd
grep -E "root|ROOT" passwd
grep 中的正则表达式
^westos
westos$
'w....s'
'w.....'
'.....s'
grep 中字符的匹配次数设定
- 字符出现 [0- 任意次 ]
? 字符出现 [0-1 次 ]
+ 字符出现 [1- 任意次 ]
{n} 字符出现 [n 次 ]
|{m,n} 字符出现 [ 最少出现 m 次,最多出现 n 次 ]
{0,n} 字符出现 [0-n 次 ]
{m,} 字符出现 [ 至少 m 次 ]
(xy){n}xy 关键字出现 [n 次 ]
.* 关键字之间匹配任意字符
grep 中字符的匹配位置设定
^ 关键字
关键字 $
< 关键字
关键字 >
< 关键字 >
grep 正则表达式与扩展正则表达式
正规的 grep 不支持扩展的正则表达式子 , 竖线是用于表示”
或”的扩展正则表达式元字符 , 正规的 grep 无法识别
加上反斜杠 , 这个字符就被翻译成扩展正则表达式 , 就像 egrp
和
grep -E 一样
2. sed 行编辑器
stream editor
用来操作纯 ASCII 码的文本 处理时 , 把当 前处理的行存储在临时缓冲区中 , 称为“模式空 间” (pattern space) 可以指定仅仅处理哪些行 sed 符合模式条件的处理 不符合条件的不予处理
处理完成之后把缓冲区的内容送往屏幕
接着处理下一行 , 这样不断重复 , 直到文件末尾Sed 命令格式
调用 sed 命令有两种形式:
sed [options] 'command' file(s)
sed [options] -f scriptfile file(s)
sed 对字符的处理 •
p 显示 •
d 删除 •
a 添加 •
c 替换 •
w 写入 •
i 插入
p 模式操作 •
sed -n ‘/:/p’ fstab •
sed -n ‘/UUID$/p’ fstab •
sed -n ‘/^UUID/p’ fstab •
sed -n ‘2,6p’ fstab •
sed -n ‘2,6!p’ fstab
d 模式操作 •
sed '/^UUID/d' /etc/fstab •
sed '/^#/d' /etc/fstab •
sed '/^$/d'/etc/fstab •
sed '1,4d'/etc/fstab •
sed –n '/^UUID/!d' /etc/fstab
a 模式操作
sed '/^UUID/a \hello sed /etc/fstab
sed '/^UUID/a \hello sed\nwestos /etc/fstab’i 模式操作
sed '/^UUID/i\hello sed\nwestos /etc/fstab’c 模式操作
sed ‘/^UUID/c\hello sed\nwestos /etc/fstab’
w 模式操作 •
sed '/^UUID/w /tmp/fstab.txt' /etc/fstab
sed -n'/^UUID/w /tmp/fstab.txt' /etc/fstab
sed '/^UUID/='/etc/fstab
sed '6r /etc/issue' /etc/fstab
sed 的其他用法
sed -n '/^UUID/=' fstab
sed -n -e '/^UUID/p' -e '/^UUID/=' fstab
sed -e 's/brown/green/; s/dog/cat/' data
sed -f rulesfile file
sed 's/^\//#/'/etc/fstab
sed 's@^/@#@g'/etc/fstab
sed 's/\//#/'/etc/fstab
sed 's/\//#/g/'/etc/fstab
sed 'G' data
sed '$!G' data
sed '=' data | sed 'N; s/\n/ /'