1.Sed Introduction
stream Data editor Stream editer (SED), which is a row editor (corresponding to a full-screen editor) that processes one line at a time. The original file content is not edited by default (-I will modify the original file directly). When processing, it first stores the current conforming rows in the temporary buffer, and after processing, the contents of the buffer are sent to the screen to print out.
2. Command format
sed [option] ' Addresscommand ' file ....
Address
start line, end line; 1,50 sed ' 1,10d '/etc/fstab
Starting line, +n line; Sed ' 1,+3d '/etc/fstab
/Regular expression/; /^root/sed '/uuid/d '/etc/fstab
/mode 1/,/mode 2/, the first time the line matched to the pattern 1 to the second time by the pattern 2 to match all the rows
line number; Specifies the row to be processed, which represents the last line of sed ' $d '/etc/fstab
Command
D; Delete rows that match the criteria
p; Show qualifying line sed ' ^uuid/p '/etc/fstab
a \string; Append string New line after qualifying line sed ' ^uuid/a \ #comment '/etc/fstab
I \string; add a new String line before the qualifying line
R FILENAME; After adding the contents of the specified file to the qualifying line (merge file) sed ' $r/etc/passwd '/etc/fstab
W FILENAME; Save eligible content to the specified file sed '/^uuid/w/tmp/333.txt '/etc/fstab
S/mode/string/; finds the first qualifying content in each row and replaces it with a String, the delimiter can be #,@, and so on, and%s represents a full-text search
Sed ' s/^uuid/uuid/'/etc/fstab sed ' s/-/#/'/etc/fstab
Modifier g global substitution, I ignore capitalization sed ' s/-/#/g '/etc/fstab
Option
Some of the common options
-N Silent mode
-I directly modify the source file
-e addresscommand-e Addresscommand execute multiple commands simultaneously
-f/scriptfile file processing with a script file
-R using extended regular expressions
3. Example
1. Delete all spaces at the beginning of history | sed ' s/^[[:space:]]*//g '
2. Add the user in the parameter by script, the user in the parameter is separated by commas
Addusersh User1,user2,user3
#!/bin/bash
For L in ' echo $ | Sed ' s/,//g ';d o
If ID $l &>/dev/null;then
echo "$l exists"
Else
Useradd $l
echo $l | passwd--stdin $l &>/dev/null
echo "$l added"
Fi
Done
SED command Learning