Xman Blog Inside

Monday, September 04, 2006

Sed Quick Reference

Generic command format:
[address]command
command = 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{
command1
command2
command3
}
Substitution format:
[address]s/pattern/replacement/flags
flags = 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/pReplace 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/gFind lines with abc, then replace pqr in the line by xyz. 'g' -> Replaces all pqr in the line.
1dDeletes the first line.
$dDeletes the last line.
/^$/dDeletes blank lines.
3,10dDeletes line 3 to line 10 inclusive.
3,10!dDeletes all lines except line 3 to line 10 inclusive.
10,$dDeletes line 10 to last line inclusive.
\(abc\)\+Match one or more abc. Regular expression needs '\'.
abc+Match literal abc+.
# A commentComment.
s!abc!xyz!Replace abc by xyz, but using ! as delimiter.
a\abcAppend abc to the matching line.
i\abcInsert abc before the matching line.
c\abcChange the matching line to abc.
=Print line with line number.
nOutput the contents of the pattern space and read next line.
r fileRead file.
w fileWrite file.
&Represent the regular expression matching string (used in replacement string).
\3Match 3th substring in the regular expression using \( \).
s/\(a\)\(b\)/\2\1/Replace ab by ba.
s/abc/xyz/2Replace the 2nd abc by xyz.
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

Labels: ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

Links to this post:

Create a Link

<< Home