- SED is a stream editor. A stream editor is used to perform basic text transformations on an input stream (a file or input from a pipeline).
- General Syntax of sed:
sed -option 'general expression' [data-file]
sed -option sed-script-file [data-file]
- Options
Option |
Meaning |
Example |
-e |
Read the different sed command from command line. |
$ sed -e 'sed-commands' data-file-name $ sed -e 's/Linux/UNIX(system v)/' file |
-f |
Read the sed command from sed script file. |
$sed -f sed-script-file data-file-name $sed -f chgdb.sed friends.tdb |
-n |
Suppress the output of sed command. When -n is used you must use p command of print flag. |
$ sed -n '/^\*..$/p' demofile2 |
Ex: delete blank lines and redirect the output
$sed '/^$/d' file > file.out
Ex: takes input from who command and check whether particular user is logged or not
$who | sed -n '/nix/p'
- sed script
[line-address, pattern]i, a, c\ /* insert, append, change the text at line number i (pattern). */
text
- Ex: create a plain file "inven" with the contents of last 4 lines.
Sr. No |
Product |
Qty |
Unit Price |
1 |
Pen |
5 |
20.00 |
2 |
Rubber |
10 |
2.00 |
3 |
Pencil |
3 |
3.50 |
4 |
Cock |
2 |
45.50 |
$vi chg.sed
1i\ /* insert the text at line number 1 */
Price of all items changes from 1st-April-2001
/Pen/s/20.00/19.5/ /* search the line with pattern "Pen" and substitute 20.00 with 19.5 */
/Pencil/s/2.00/2.60/
/Rubber/s/3.50/4.25/
/Cock/s/45.50/51.00/
$sed -f chg.sed inven
- At least nth occurrences will be matched.
Syntax: \{n,\}
Ex:
$sed -n '/10\{2\}1/p' file /* /10\{2\} will look for 1 followed by 0 (zero) and \{2\}, tells sed look for 0 (zero) for twice */
- Matches any number of occurrences between n and m.
Syntax: \{n,\m}
Ex:
$sed -n '/10\{2,4\}1/p' file /* match "1001", "10001", "100001" */