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 '/./!d' 删除所有空行
sed ‘/^$/d’ file 去掉空行
sed 's/[ \t]*$//g' 删除行尾空行或制表符 有的系统不识别\t,这样的话,输入制表符,输入方式为:ctrl+v ctrl+i
sed 's/^[ \t]*//g'
WINDOWS传到UNIX在每行的结尾可能会出现^M
sed 's/^M//g' ^ ctrl+v M ctrl+m 的方式输入
*插入
sed ‘nirhel007′ file 将rhel007插入到第n行之前
sed ‘nathis is a test’ file 将this is a test 插入到第n行之后
sed ‘$irhel007′ file 插入到最后一行之前
sed ‘$arhel007′ file 插入到最后一行之后
sed 's/^/diff /g' ant.list #每行行首加入字符串diff
ed 's/$/ >> dd.list/g' ant.list #每一行末尾加入字符串>> dd.list
*更改
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的行