sed,grep用法小结

1 打印关键字所在行及其后n行
sed -n '/XX/,+np' file
grep "xx" -An yourfile
2 获取关键字所在行和其上n行
grep "xx" -Bn yourfile
3 获取关键字所在行的行号
sed  -n '/pattern/=' file
4 打印并标出行号
grep -n file
5 多关键字搜索
grep -E "xxx|yyy" file
6 |表示或关系,比如 'gd|good|dog' 表示有gd,good或dog的串
egrep 'gd|good|dog'
7 sed -i “s/a/b/g” ’grep c -rl /d‘
-r 搜索子目录
-l 输出匹配的文件名
8 在匹配关键字上一行插入一行
sed '/xx/i yyy' -i file
9 在匹配关键字下一行插入一行
sed '/xx/a yyy' -i file
10 删除文件中的空行
sed /^$/d filename
11 删除内容为多个空格tab组成的行
sed /^[[:space:]]*$/d filename
12 sed -e 多重编辑
sed -e 's/aa/bb/g' -e '/cc/dd/g'  file 或 sed -e 's/aa/bb/g;/cc/dd/g' file 
13 在file的每行行尾添加字符“xxx”
sed -i 's/$/xxx/g' file
14 在file的每行行首添加字符“xxx”
sed -i 's/^/xxx/g' file

猜你喜欢

转载自sundful.iteye.com/blog/2070390