Home > Articles

  • Print
  • + Share This
This chapter is from the book

sed

Use the sed utility to make automated modifications to files. The basic format for the sed command is sed 's/RE/string/' file.

The “RE” refers to the term regular expression, a feature that uses special characters to match patterns. See Chapter 15, “Search Text Files Using Regular Expressions,” for more details about regular expressions.

Example of the sed command:

[student@localhost ~]$ head -n 5 /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
[student@localhost ~]$ head -n 5 /etc/passwd | sed 's/bin/----/'
root:x:0:0:root:/root:/----/bash
----:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/s----:/sbin/nologin
adm:x:3:4:adm:/var/adm:/s----/nologin
lp:x:4:7:lp:/var/spool/lpd:/s----/nologin

sed is a very powerful utility with a large number of features. The following table describes some of the more useful sed utilities:

Feature Description
'/RE/d' Deletes lines that match the RE from the output of the sed command.
'/RE/c\string' Changes lines that match the RE to the value of string.
'/RE/a\string' Add string on a line after all lines that match the RE.
'/RE/i\string' Add string on a line before all lines that match the RE.

The sed command has two important modifiers (characters added to the end of the sed operation):

  • g—Means “global.” By default only the first RE pattern match is replaced. When the g modifier is used, all replacements are made. See Figure 10.3 for an example.

10fig03.jpg

Figure 10.3 The g Modifier

  • i—Means “case-insensitive.” This modifier matches an alpha character regardless of its case. So, the command sed 's/a/-/i' would match either “a” or “A” and replace it with the “-” character.

The sed command can also change the original file (instead of displaying the modified data to the screen). To change the original file, use the -i option.

  • + Share This
  • 🔖 Save To Your Account