1. The basic syntax for sed substitution is:
's/original string/replace string/'
Inside the single quotation mark, S is the replacement, the middle of the three slash is the replacement style, and the special characters need to be escaped with a backslash "\".
2. The single quote "'" is no way to escape with a backslash "\", as long as the single quotation mark in the command is changed to double quotation marks on the line, the format is as follows:
The character to be processed contains single quotation marks
"s/Original string contains '/substitution string contains '/
3. The three slash delimiter in the command can be replaced by a different symbol, sometimes there are more slashes when replacing the directory string, this time it is more convenient to change to other separators, just follow the s definition.
# Replace the delimiter with a question mark "?":
's? original string? Replace String? '
4. You can replace each matched keyword with g at the end, or replace only the first of each line, for example:
Replace all matching keywords
's/original string/replace string/g'
5. Use of some special characters
"^" indicates the beginning of the line
The "$" symbol if the end of the line is represented in quotation marks, but the last line is represented by the quote
Note the "&" symbol here, if there is no "&", the matching string will be replaced directly
Sed‘S/^/added head &/g‘#Add at all beginning of lineSed‘s/$/& added tail/g‘#Add at the end of all linesSed'2s/original string/replace string/g' # replace 2nd line sed '$s/original string/replace string/g' # replace last line sed ' 2,5s/Original string/replace string/g' # replace 2 to 5 lines sed '2, $s/original string/replace string/g' # replace 2 to last line
6. Bulk replacement strings
"s/lookup field/replace field/g" 'grep lookup field-rl path '
Sed-i "s/oldstring/newstring/g" ' grep oldstring-rl Yourdir
7. Sed processed output is directly output to the screen, using the parameter "I" directly in the file replacement.
Replace all occurrences in a file
's/original string/replacement string/g' filename
8. Multiple substitutions can be performed in the same command, with a semicolon ";" Delimited, in the form of:
Execute two substitution rules at a time
's/^/added header &/g;s/$/& added tail/g
Sed string substitution