参考文章:http://www.thegeekstuff.com
sed工作原理
This is called as one execution cycle. Cycle continues till end of file/input is reached:
1. Read a entire line from stdin/file.
2. Removes any trailing newline.
3. Places the line, in its pattern buffer.
4. Modify the pattern buffer according to the supplied commands.
5. Print the pattern buffer to stdout.
命令的格式:
ADDRESS(行号):
n
: 匹配第几行
m,n
: 从m到n行
m~n
:从m行开始,每隔n行
‘$‘
: 最后一行
PATTERN(字符串):
/sometext/
: 匹配有sometext字符串的行
sed -n ‘ADDRESS‘p filename // print, e.g: sed -n ‘4‘p text.txt。 ‘ADDRESSp‘,即将p放在单引号中也是可以的,或者将单引号换成双引号"ADDRESSp"也是一样,下同。
sed -n ‘/PATTERN/p‘ filename // e.g: sed -n ‘/aa/p‘ text.txt
sed -n ‘ADDRESS‘d filename //delete,不会删除文件中的内容,只是在标准输出中删除该行。
sed -n ‘/PATTERN/d‘ filename
sed ‘ADDRESS a some text‘ filename //append,在匹配行的下一行添加"some text",注意单引号
sed ‘/PATTERN/ a some text‘ filename
sed ‘ADDRESS i some text‘ filename // insert,在匹配行前插入一行
sed ‘/PATTERN/ i some text‘ filename
sed ‘ADDRESS c some text‘ filename // 替换匹配行
sed ‘PATTERN c some text‘ filename
sed -n ‘ADDRESS‘= filename //打印匹配的行号, 只接受一个地址,如果打印多行使用{}括起来,如下
sed -n ‘ADDRESS,/PATTERN/ {
=
p
}‘ filename
sed 正则表达式查找和替换:
‘s‘
命令应该是sed中最重要的命令,语法如下:
sed ‘ADDRESSs/REGEXP/REPLACEMENT/FLAGS‘ filename
sed ‘PATTERNs/REGEXP/REPLACEMENT/FLAGS‘ filename
例子:
sed ‘1s/aa/bb/‘ text.txt //用bb替换aa,只在aa第一次出现的地方进行替换
sed ‘2s/aa/bb/‘ text.txt //用bb替换aa,只在aa第二次出现的地方进行替换
sed ‘s/aa/bb/g‘ text.txt //用bb替换aa,g(global )是全局替换的意思。不加g默认也是全局替换。
sed -n ‘s/aa/bb/gpw result.txt‘ text.txt //g全局替换,p打印,w将替换结果写到result.txt文件中
sed ‘s/...$//‘ text.txt //正则表达式匹配:将最后位置的前三个字符替换为空,即删除每行的最后三个字符。
执行多条sed命令
sed -e: use multiple -e
options to build up a script out of many parts。
-e
option is optional for sed with single command. sed will execute the each set of command while processing input from the pattern buffer
-e
script, --expression
=script
add the script to the commands to be executed
例子:
sed -e ‘s/foo/bar/‘ -e ‘/FOO/d‘
解释:先用bar替换foo,然后再删除有字符串FOO的行