- 1. Sed Introduction
- sed is an online editor that processes one line of content at a time. During processing, it stores the currently processed line in a temporary buffer called the “pattern space,” then uses sed commands to process the content in the buffer. After processing, it sends the buffer content to the screen. It then proceeds to the next line, repeating this process until the end of the file. The file content itself is not changed unless you use redirection to store the output. Sed is primarily used for automatically editing one or more files, simplifying repetitive operations on files, and writing conversion programs. The following introduces the GNU version of Sed 3.02.
- 2. Addressing
- You can use addressing to locate the lines you wish to edit. The address is composed of numbers; two line numbers separated by a comma represent the range of lines starting and ending with those two lines (inclusive). For example, 1,3 means lines 1, 2, and 3. The dollar sign ($) represents the last line. The range can be determined by numbers, regular expressions, or a combination of both.
- 3. Sed Commands
- There are two forms for calling sed commands:
- *
- sed [options] 'command' file(s)
- *
- sed [options] -f scriptfile file(s)
- a/
- Appends a line of text after the current line.
- b label
- Branches to a marked position in the script; if the branch label does not exist, branches to the end of the script.
- c/
- Changes the text of the current line with new text.
- d
- Deletes lines from the pattern space position.
- D
- Deletes the first line of the pattern space.
- i/
- Inserts text above the current line.
- h
- Copies the contents of the pattern space to the hold buffer in memory.
- H
- Appends the contents of the pattern space to the hold buffer in memory.
- g
- Gets the contents of the hold buffer and replaces the text in the current pattern space.
- G
- Gets the contents of the hold buffer and appends it after the text in the current pattern space.
- l
- Lists non-printable characters.
- n
- Reads the next input line and processes the new line with the next command rather than the first command.
- N
- Appends the next input line to the pattern space, embedding a newline between them, and changes the current line number.
- p
- Prints the lines of the pattern space.
- P (uppercase)
- Prints the first line of the pattern space.
- q
- Exits Sed.
- r file
- Reads lines from file.
- t label
- if branch; starting from the last line, once the condition is met, or with a T or t command, it will cause a branch to the command with the label, or to the end of the script.
- T label
- Error branch; starting from the last line, once an error occurs, or with a T or t command, it will cause a branch to the command with the label, or to the end of the script.
- w file
- Writes and appends the pattern space to the end of file.
- W file
- Writes and appends the first line of the pattern space to the end of file.
- !
- Indicates that the following command applies to all lines that were not selected.
- s/re/string
- Replaces the regular expression re with string.
- =
- Prints the current line number.
- #
- Extends the comment until the next newline character.
- The following are substitution flags
- *
- g means global replacement within the line.
- *
- p means print the line.
- *
- w means write the line to a file.
- *
- x means exchange the text in the pattern space with the text in the hold buffer.
- *
- y means translate one character into another (but not used for regular expressions).
- 4. Options
- -e command, –expression=command
- Allows multiple edits.
- -h, –help
- Prints help and displays the address for bug lists.
- -n, –quiet, –silent
- Cancels the default output.
- -f, –filer=script-file
- Directs sed to use a script file.
- -V, –version
- Prints version and copyright information.
- 5. Meta-character Set ^
- Anchors the beginning of a line. E.g., /^sed/ matches all lines starting with sed.
- $
- Anchors the end of a line. E.g., /sed$/ matches all lines ending with sed.
- .
- Matches any single character except newline. E.g., /s.d/ matches s followed by any character, then d.
- *
- Matches zero or more characters. E.g., /*sed/ matches all lines where the pattern is one or more spaces followed immediately by sed.
- []
- Matches any character within a specified range. E.g., /[Ss]ed/ matches both sed and Sed.
- [^]
- Matches any character not within a specified range. E.g., /[^A-RT-Z]ed/ matches lines starting with a letter not in the range A-R and T-Z, followed by ed.
- /(../)
- Save matched characters, e.g., s//(love/)able//1rs, loveable becomes lovers.
- &
- Save the search string to replace other characters, e.g., s/love/**&**/, love becomes **love**.
- /<
- Anchor at the start of a word, e.g.,://<love/ matches lines containing words starting with love.
- />
- Anchor at the end of a word, e.g., /love/>/ matches lines containing words ending with love.
- x/{m/}
- Repeat character x, m times, e.g., /0/{5/}/ matches lines containing 5 o’s.
- x/{m,/}
- Repeat character x, at least m times, e.g., /o/{5,/}/ matches lines with at least 5 o’s.
- x/{m,n/}
- Repeat character x, at least m times, and at most n times, e.g., /o/{5,10/}/ matches lines with 5—10 o’s.
- 6. Examples
- Delete: d command
- *
- $ sed '2d' example—–Delete the second line of the example file.
- *
- $ sed '2,$d' example—–Delete all lines from the second line to the end of the example file.
- *
- $ sed '$d' example—–Delete the last line of the example file.
- *
- $ sed '/test/'d example—–Delete all lines containing ‘test’ in the example file.
- Substitute: s command
- *
- $ sed 's/test/mytest/g' example—–Replace ‘test’ with ‘mytest’ on the entire line. Without the g flag, only the first matched ‘test’ on each line is replaced with ‘mytest’.
- *
- $ sed -n 's/^test/mytest/p' example—–The (-n) option combined with the p flag means to print only lines where a substitution occurred. That is, if ‘test’ at the beginning of a line is replaced with ‘mytest’, print that line.
- *
- $ sed 's/^192.168.0.1/&localhost/' example—–The & symbol represents the part of the replacement string that was found. All lines starting with 192.168.0.1 will be replaced by themselves plus localhost, becoming 192.168.0.1localhost.
- *
- $ sed -n 's//(love/)able//1rs/p' example—–love is tagged as 1, all occurrences of loveable will be replaced with lovers, and the replaced lines will be printed.
- *
- $ sed 's#10#100#g' example—–Regardless of the character, whatever immediately follows the s command is considered the new delimiter. So, “#” is the delimiter here, replacing the default “/” delimiter. This means replace all 10 with 100.
- Selecting a range of lines: Comma
- *
- $ sed -n '/test/,/check/p' example—–All lines within the range determined by the patterns test and check are printed.
- *
- $ sed -n '5,/^test/p' example—–Print all lines from the fifth line up to the first line that starts with test.
- *
- $ sed '/test/,/check/s/$/sed test/' example—–For lines between the patterns test and check, replace the end of each line with the string sed test.
- Multi-point editing: e command
- *
- $ sed -e '1,5d' -e 's/test/check/' example—–The (-e) option allows multiple commands to be executed on the same line. As shown in the example, the first command deletes lines 1 to 5, and the second command replaces test with check. The order of command execution affects the results. If both commands are substitution commands, the first substitution will affect the result of the second.
- *
- $ sed –expression='s/test/check/' –expression='/love/d' example—–A better command than -e is –expression. It allows assigning values to sed expressions.
- Read from file: r command
- *
- $ sed '/test/r file' example—–The contents of file are read in and displayed after lines matching test. If there are multiple matching lines, the content of file will be displayed below all matching lines.
- Write to file: w command
- *
- $ sed -n '/test/w file' example—–All lines in example containing test are written to file.
- Append command: a command
- *
- $ sed '/^test/a//—>this is a example' example<—–'this is a example' is appended after lines starting with test. The sed command requires a backslash after the a command.
- Insert: i command
- $ sed '/test/i//
- new line
- ————————-' example
- If test is matched, the text after the backslash is inserted before the matching line.
- Next: the n command
- *
- $ sed '/test/{ n; s/aa/bb/; }' example—–If test is matched, move to the next line of the matching line, replace aa with bb on that line, print the line, and then continue.
- Transform: the y command
- *
- $ sed '1,10y/abcde/ABCDE/' example—–Transform all characters abcde to uppercase within lines 1 to 10. Note that regex metacharacters cannot be used with this command.
- Quit: the q command
- *
- $ sed '10q' example—–After printing the 10th line, quit sed.
- Hold and Get: the h command and G command
- *
- $ sed -e '/test/h' -e '$G example—– When sed processes a file, each line is stored in a temporary buffer called the pattern space. Unless a line is deleted or output is suppressed, all processed lines are printed to the screen. The pattern space is then cleared and a new line is loaded for processing. In this example, after a line matching test is found and placed in the pattern space, the h command copies it to a special buffer called the hold space. The second statement means: when the last line is reached, the G command takes the content of the hold space and appends it back into the pattern space, after the line currently there. In this case, it appends it to the last line. Simply put, any line containing test is copied and appended to the end of the file.
- Hold and Exchange: the h command and x command
- *
- $ sed -e '/test/h' -e '/check/x' example —–Exchange the contents of the pattern space and the hold space. In other words, swap the lines containing test and check.
- 7. Scripts
- A Sed script is a list of sed commands, launched with the -f option followed by the script filename. Sed is very particular about the commands in the script; there must be no trailing whitespace or text at the end of a command. If multiple commands are on one line, they must be separated by semicolons. Lines starting with # are comments and cannot span multiple lines.
sed can truly boost our productivity significantly. For instance, I just wrote this single line, and it replaced content in many files — so convenient.
- sed 's/localhost/127.0.0.1/g' mysql_virtual_*.cf
