Reference article: http://www.thegeekstuff.com
how SED works
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 with its pattern buffer.
4. Modify the pattern buffer according to the supplied commands.
5. Print the pattern buffer to stdout.
format of the command:
ADDRESS (line number):
n
: Matches the first few lines
m,n
: from M to n rows
m~n
: Starting with M lines, every n rows
‘$‘
: Last line
PATTERN (String):
/sometext/
: Matches a row with a sometext string
Sed- N ' ADDRESS 'P filename//Print, E.g:sed-n ' 4 ' P text.txt. ' ADDRESSP ', it is also possible to put p in single quotation marks, or to replace single quotes with double quotes "ADDRESSP" is also the same, the same. Sed- N '/pattern/p 'FileName//E.g:sed-n '/aa/p ' text.txtSed- N ' ADDRESS 'd filename//delete, the contents of the file are not deleted, only the row is deleted in standard output. Sed- N '/pattern/d 'Filenamesed' ADDRESS A some text 'FileName//append, add "some text" to the next line of the matching row, note the single quoteSed'/pattern/a some text 'Filenamesed' ADDRESS i some text 'FileName//INSERT, inserting a row before matching rowsSed'/pattern/i some text 'Filenamesed' ADDRESS c some text 'FileName//Replace matching rowsSed' PATTERN c some text 'Filenamesed- N ' ADDRESS '=FileName//print matching line numbers, accept only one address, if you print multiple lines using {}, as followsSed- N ' address,/pattern/{=p} 'FileName
sed Regular expression lookup and substitution:
‘s‘
The command should be the most important command in SED, with the following syntax:
‘ADDRESSs/REGEXP/REPLACEMENT/FLAGS‘‘PATTERNs/REGEXP/REPLACEMENT/FLAGS‘ filename
Example:
‘1s/aa/bb/‘text.txt //用bb替换aa,只在aa第一次出现的地方进行替换‘2s/aa/bb/‘text.txt //用bb替换aa,只在aa第二次出现的地方进行替换‘s/aa/bb/g‘text.txt //用bb替换aa,g(global )是全局替换的意思。不加g默认也是全局替换。‘s/aa/bb/gpw result.txt‘text.txt //g全局替换,p打印,w将替换结果写到result.txt文件中‘s/...$//‘text.txt //正则表达式匹配:将最后位置的前三个字符替换为空,即删除每行的最后三个字符。
execute multiple SED commands
sed-e: use multiple -e
options to build up a script out of many parts.
-e
option is optional-sed with single command. Sed would 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
Example:
sed -e ‘s/foo/bar/‘ -e ‘/FOO/d‘
explanation : replace Foo with bar before deleting rows with string foo
Sed:linux Common Tools