Examples of How the Linux Sed Command Is Used

Manipulate text files with simple commands

Man typing on computer
Paul Harizan/Stockbyte/Getty Images

The Linux operating system makes use of terminal commands to work with a computer's file system. The primary use of the Linux command sed, which is short for "stream editor," is to modify each line of a file or stream by replacing specified parts of the line. It makes basic text changes to a file or input from a pipeline.

Examples of using sed to make text file changes

Let's say you have a file named songs.txt that contains these 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

You want to change all price occurrences of $6.30 to $7.30. To do so, you can use the sed command in this way:

sed 's/6.30/7.30/' songs.txt > songs2.txt
This code makes the change and saves the modified file as songs2.txt. The resulting new file contains:

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 to replace all occurrences of "Cash" with "Trash" you could also use the sed command in this way:

sed 's/Cash/Trash/' songs.txt > songs2.txt

The resulting modified file songs2.txt would contain the following text:

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

Filtering with the sed command

Sed is also frequently used to filter lines in a file or stream. For example, if you only want to see the lines containing "John," you would use the following sed command:

sed -n '/John/p' songs.txt > johns.txt

The new johns.txt file would contain the following lines:

5, Johnny Trash, Title 482, Price $6.50

7, John Lennon, Title 271, Price $7.90