Use of the sed command, sed
Sed streaming Editor/text filtering
Stream Editor
Based onPattern MatchingFilter/Modify text
Syntax format:
Sed 'edit directive 'file 1 file 2
All contents before and after modification are output.
Sed-n 'edit directive 'file 1 file 2
Only the modified and filtered content is displayed.
Sed-I 'edit directive 'file 1 file 2
The modified content will be replaced directly without output.
Edit command writing
Format: [address 1 [, address 2] operation type
SemicolonSeparate
Sed-n '3 P; 5 p '/etc/hosts
The most common operation type
P output/print text lines
N remove a line of text (skip the current line)
D. Delete
S string replacement
A. append new text
Output text content by line
Sed-n 'P; n' file.txt outputs all odd rows
Sed-n'n'; P' file.txt outputs all even rows
Use Regular Expressions
Sed-n'/w2k8/, $ P' file.txt
Sed-n'/\ <This> \/P' file.txt \ <word> \ indicates matching a word
Delete a qualified row
Sed '2, 3d 'file.txt Delete 2-3 rows
Sed '/w2k8/d; $ d' file.txt Delete the row and last row containing w2k8
Delete rows that do not meet the conditions
Sed/2, 3! D/file.txt delete other rows except 2-3
Replace qualified text
Sed '3, 4S/yes/no/G' file.txt replace all yes in 3-4 rows with no
Special effects of replacement
Sed '1, 2 s/^/#/G' file.txt is inserted at the beginning of line 1-2 # (usually batch comment)
Sed's/yes // G' file.txt delete all yes in file.txt (replaced with null)