1. Computing

Discuss in my forum

Example uses of sed

An introductory tutorial

By

A common use of sed is to modify each line of a file or stream by replacing specified parts of the line. For example if you have a file that contains the lines:

1, Justin Timberlake, Title 545, Price $6.30
2, Taylor Swift, Title 723, Price $7.90
3, Mick Jagger, Title 610, Price $7.90
4, Lady Gaga, Title 118, Price $6.30
5, Johnny Cash, Title 482, Price $6.50
6, Elvis Presley, Title 335, Price $6.30
7, John Lennon, Title 271, Price $7.90
If the file name is "songs.txt" and you wanted to change all occurrences of 6.30 to 7.30 you could use the command:

sed 's/6.30/7.30/' songs.txt > songs2.txt
which writes the modified file to "songs2.txt". So the output file would contain:

1, Justin Timberlake, Title 545, Price $7.30
2, Taylor Swift, Title 723, Price $7.90
3, Mick Jagger, Title 610, Price $7.90
4, Lady Gaga, Title 118, Price $7.30
5, Johnny Cash, Title 482, Price $6.50
6, Elvis Presley, Title 335, Price $7.30
7, John Lennon, Title 271, Price $7.90
If you wanted replace all occurrences of "Cash" with "Trash" you would be use:

sed 's/Cash/Trash/' songs.txt > songs2.txt
which would create a file with content:

1, Justin Timberlake, Title 545, Price $7:30
2, Taylor Swift, Title 723, Price $7.90
3, Mick Jagger, Title 610, Price $7.90
4, Lady Gaga, Title 118, Price $7:30
5, Johnny Trash, Title 482, Price $6.50
6, Elvis Presley, Title 335, Price $7:30
7, John Lennon, Title 271, Price $7.90
Sed is also frequently used to filter lines in a file or stream. For example if you only want see the lines containing "John" you could use:

sed -n '/John/p' songs.txt > johns.txt
which will write the following lines to file johns.txt:

5, Johnny Trash, Title 482, Price $6.50
7, John Lennon, Title 271, Price $7.90
  1. About.com
  2. Computing
  3. Linux
  4. Linux / Shell Commands
  5. Examples of how to use the command sed

©2014 About.com. All rights reserved.