Sed Quick Reference
Generic command format:
Group command format:
Transform format:
[address] can be lines found by regular expression matches, range of lines.
There are other commands like multi-line commands (N, D, P), copying/appending pattern space to hold space vice versa (h,H,g,G,x), label(:labelname), branch to label (b), conditional branch (t).
Reference: UNIX Power Tools: sed & awk by Dale Dougherty
[address]commandcommand = d, a, i, c, r, w, q, ... d: Delete. a: Append. i: Insert. c: Change. r: Read. w: Write. q: Quit.
Group command format:
address{Substitution format:
command1
command2
command3
}
[address]s/pattern/replacement/flagsflags = n, g, p, or w file. n: A number n represents nth occurrence. g: Global. p: Print. w file: Write to file.
Transform format:
[address]y/abc/xyz/Translate a->x, b->y, and c->z.
[address] can be lines found by regular expression matches, range of lines.
| s/abc/xyz/p | Replace abc by xyz, and print (required 'p' if we use "sed -n" to suppress printing all lines). |
| s/abc/pqr/ s/pqr/xyz/ | Replace abc by pqr, then replace pqr by xyz. Effectively, abc and pqr becomes xyz. |
| /abc/s/pqr/xyz/g | Find lines with abc, then replace pqr in the line by xyz. 'g' -> Replaces all pqr in the line. |
| 1d | Deletes the first line. |
| $d | Deletes the last line. |
| /^$/d | Deletes blank lines. |
| 3,10d | Deletes line 3 to line 10 inclusive. |
| 3,10!d | Deletes all lines except line 3 to line 10 inclusive. |
| 10,$d | Deletes line 10 to last line inclusive. |
| \(abc\)\+ | Match one or more abc. Regular expression needs '\'. |
| abc+ | Match literal abc+. |
| # A comment | Comment. |
| s!abc!xyz! | Replace abc by xyz, but using ! as delimiter. |
| a\abc | Append abc to the matching line. |
| i\abc | Insert abc before the matching line. |
| c\abc | Change the matching line to abc. |
| = | Print line with line number. |
| n | Output the contents of the pattern space and read next line. |
| r file | Read file. |
| w file | Write file. |
| & | Represent the regular expression matching string (used in replacement string). |
| \3 | Match 3th substring in the regular expression using \( \). |
| s/\(a\)\(b\)/\2\1/ | Replace ab by ba. |
| s/abc/xyz/2 | Replace the 2nd abc by xyz. |
Reference: UNIX Power Tools: sed & awk by Dale Dougherty
Labels: Quick reference, Sed

0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
Links to this post:
Create a Link
<< Home