工作,学习,生活,这里将会有一些记录. 备用域名:http://meisw.wdlinux.cn 注册 | 登陆

sed的一些总结

在写一些常用的脚本中,经常会用到sed,但是这东西,不经常用,就会忘掉,现在记在这里,以后想找sed了就来这里看看。
*替换
sed ‘s/word1/word2/2′ file 将第2行中的word1替换为word2
sed ‘s/word1/word2/g’ file word1全局替换为word2
sed -n ‘s/word1/word2/p’ file 全局替换并打印
sed ‘s/word1/word2/w test’ file 全局替换并写入文件test
sed ‘s/\/bin\/bash/\/bin\/sh/’ /etc/passwd 路径替换 特殊字符需要转义
sed ‘s!/bin/bash!/bin/sh!’ /etc/passwd 同上 感叹号被用作定界符
sed ‘ns/word1/word2/’ file 指定替换file文件中的第n行
sed ‘m,ns/word1/word2′ file 指定替换file文件中的第m到n行
sed ‘n,$s/word1/word2′ file 指定替换file文件中的第n到最后一行
sed ‘/word1/s/bash/sh/’ file 指定替换出现word1行的bash替换为sh
sed ‘n{
>s/word1/word2
>s/word3/word4
}’ file 指定替换第n行中的word1为word2 word3为word4
sed ‘s/word1/word2/;s/word3/word4/’ file 同上
sed ‘n,${
>s/word1/word2
>s/word3/word4
}’ file 指定替换从第n开始到最后一行结束的word1为word2 word3为word4
sed -e ‘n,$s/word1/word2/;s/word3/word4/’ file 同上
*删除
sed ‘d’ file 清空所有数据流(不是清空file文件内容)
sed ‘nd’ file 删除第n行
sed ‘m,nd’ file 删除第m到n行
sed ‘n,$d’ file 删除从n到最后一行
sed ‘/word1/d’ file 删除匹配word1的行

*插入
sed ‘nirhel007′ file 将rhel007插入到第n行之前
sed ‘nathis is a test’ file 将this is a test 插入到第n行之后
sed ‘$irhel007′ file 插入到最后一行之前
sed ‘$arhel007′ file 插入到最后一行之后

*更改
sed ‘ncthis is a test’ file 将第n行更改为this is a test
sed ‘/this is a test/cthat is a test’ file 匹配更改

*变换
sed ‘y/123/456/’ test
匹配修改 1-4,2-5,3-6 单个字符进行全局匹配

*打印
sed -n ‘/word/p’ file 全局匹配打印
sed -n ‘m,np’ file 打印m到n行
sed ‘=’ file 打印行号
sed -n ‘l’ file 打印不可打印的ANSIC字符
sed -n ‘np’ file 打印第n行
sed -n ‘$p’ file 打印最后一行

*文件操作
sed ‘m,nw test’ file 将file的m到n行写入到test中
sed -n ‘/word/w test’ file 匹配将包含word字符的写入test文件
sed ‘nr test’ file 将test文件中的内容写入file文件的第n行之后
sed ‘/word/r test’ file 将test文件中的内容匹配到word内容之后
sed ‘$r test’ file 将test文件中的内容追加到file的最后
sed -n ‘{
1!G
h
$p
}’ file 行逆序
sed -n ‘s/cat/”cat”/’ file 给文本中的cat增加双引号
sed -n ‘s/.at/”&”/g’ file 给文本中的.at的原单词上增加双引号
sed ‘G’ file 增加一行空行
sed ‘$!G’ file 在文本的最后一行不再增加空行
sed ‘/^$/d;$!G’ file 文本中的空行不增加行距
sed ‘=’ file 行计数
sed ‘=’ file | sed ‘N;s/\n/ /’ 计数和行在同一行上
sed -n ‘s/<[^>]*>//g;/^$/d’ file 去除html中的标签和空行

*sed正则表达式
1. .*{}[]^$\+?| 这些特殊的字符需要用\转义
2. 定位符
sed -n ‘/^test/p’ file 匹配test开头的行
sed -n ‘/test$/p’ file 匹配test结尾的行
sed -n ‘/^this is a test$/p’ 匹配以test开头和结尾的行
sed -n ‘/^$/d’ file 去掉空行
3 点字符
sed -n ‘/.li/p’ file 匹配除了换行之外的所有字符
4 字符类
[]代表或者的意思
sed -n ‘/[ch]at/p’ file 匹配hat或者cat的单词
sed -n ‘/[Yy][Ee][Ss]/p’ 匹配任何形式的yes
sed -n ‘/[c-h]at/p’ file
sed -n ‘/[a-ch-m]/p’ file 匹配a-c,h-m开头的单词
sed -n ‘/^[0-9][0-9][0-9][0-9][0-9][0-9]$/p’ 匹配邮编,电话
5 否定字符类
sed -n ‘/[^ch]at/p’ 不匹配以cat和hat开头的单词
sed -n ‘/cat/!p’ 不匹配匹配cat的行
6 * 前面的字符不出现或者出现多次

 

-------------------------------

搜索并替换

sed -i '/memory_limit/s/128/64/' /www/wdlinux/etc/php.ini

« 上一篇 | 下一篇 »

Trackbacks

点击获得Trackback地址,Encode: UTF-8

发表评论

评论内容 (必填):