分类:
2008-12-10 13:25:57
quote.txt
The honeysuckle hand played all night long for only $90.
It was an evening of splendid music and company.
Too bad the disco floor fell through at 23:10.
The local nurse Miss P.Neave was in attendance.
显示行
$sed -n '2p' quote.txt
范围
$sed -n '1,3p' quote.txt
匹配单词
$sed -n '/The/'p quote.txt
匹配某行单词
$sed -n '4,/The/'p quote.txt
匹配元字符
$sed -n '/\$/'p quote.txt
显示整个文件
$sed -n '1,$p' quote.txt sed -n '1,$'p quote.txt
任意字符
$sed -n '/.*ing/'p quote.txt 任意字符出现一次或N次 以ing结尾
首末行
$sed -n '1p' quote.txt
$sed -n '$p' quote.txt
打印行号
$sed -n '/music/=' quote.txt
2
$sed -n -e '/music/p' -e '/music/=' quote.txt
It was an evening of splendid music and company.
2
附加文件
!/bin/sed -f
/文件中匹配的字符/ a\
插入的字符 +x; *.sed quote.txt
删除行
$sed '1d' quote.txt 删除第一行
$sed '1,3d' quote.txt 删除1到3行
$sed '$d' quote.txt 删除最后一行
$sed '/Neave/d' quote.txt 删除带Neave的行
替换文本
$sed 's/night/NIGHT/' quote.txt s替换/night/NIGHT/
$sed 's/\$//' quote.txt $换成空格
$sed 's/The/Wow!/g' quote.txt g替换所有
$sed 's/splendid/SPLENDID/w sed.out' quote.txt w sed.out此行写入文件
$sed -n 's/nurse/"Hello" &/p' quote.txt
The local "Hello" nurse Miss P.Neave was in attendance.
$sed -n 's/played/from Hockering &/p' quote.txt
将sed结果写入文件命令
$sed '1,2 w filedt' quote.txt 第一二行写入文件
$sed '/Neave/ w dht' quote.txt 匹配//的写入文件
从文件中读文本
$sed '/company./r sedex.txt' quote.txt
在quote.txt的company后换行,写入sedex.txt的内容
匹配后退出
$sed '/.a.*/q' quote.txt
任意字符后跟a,再跟任意字符0次或任意次匹配:
Line 1.band Line 2.bad Liner3.was Line 4.was
The honeysuckle hand played all night long for only $90.
vi dos.txt
12332##DISO##45.12^M
00332##LPSO##23.11^M
01299##USPD##34.46^M
用一个空格替换所有的##,删除最前边的0,删除尾部^M
$sed 's/##*/ /g' dos.txt
$sed 's/^0*/ /g' dos.txt
$sed 's/\^M//g' dos.txt
$cat dos.txt |sed 's/##*/ /g'|sed 's/^0*/ /'|sed 's/\^M//g'
处理报文输出
Database Size(MB) Date Created
-------------------------------------
GOSOUTH 2244 12/11/97
TRISUD 5632 8/9/99
(2 rows affected)
1>使用s/-*//g删除 -----------
2>使用/^$/d删除空行
3>使用$d删除最后一行
4>使用1d删除第一行
5>使用awk {print $1}打印第一列
cat sql.txt | sed 's/--*//g' | sed '/^$/d' | sed '$d' | sed '1d' | awk '{print $1}'
去除行首数字
$vi UNH.txt
12345UND SPLLFC 234344
9999999UND SKKLT 3423
1UND SPLLY 434
$sed 's/^[0-9]*//g' UND.txt
附加文本每一行末尾加上字符串'passwd'
vi ok.txt
AC456
AC492169
AC9967
AC88345
$sed 's/[0-9]*/& Passwd/g' ok.txt
从sed输出中设置shell变量
$NAME="It's a go situation"
$REPLACE="GO"
$NEW_NAME='echo $NAME | sed "s/go/$REPLACE/g"'
$echo $NEW_NAME
快速一行命令
's/\.$//g' 删除以.结尾的行
'-e /abcd/d' 删除包含abcd的行
's/[][][]*/[]/g' 删除一个以上的空格,用一个空格代替
's/^[][]*//g' 删除行首空格
's/\.[][]*/[]//g 删除.后跟2或多个空格,以一个空格代替
's/COL\(...\)//g'删除COL和它后边的3个字母的行
's/^\//g' 删除第一个\
's/[]/[]//g' 删除所有空格并用tab替代
's/^[]//g' 删除行首tab键
's/[]*//g' 删除所有tab键
插入文本
$echo "Mr Willis"|sed 's/Mr/& Bruce/g'
删除首字符
$echo "attkla.dc"|sed 's/^./g'
删除文件扩展名
$echo "attkla.dc"|sed 's/.dc//g'
增加扩展名
$echo "attkla"|sed 's/$/.dc/g'
替换字符系列
$x="Department+payroll%Building G"
+ 换成of %换成located
$echo $x | sed 's/\+/ of /g' | sed 's/\%/ Located at /g '