O'Reilly logo

Linux in a Nutshell, Fourth Edition by Aaron Weber, Stephen Figgins, Ellen Siever

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Name

s

Synopsis

[address1[,address2]]s/
                  pattern
                  /
                  replacement
                  /[flags]

Substitute replacement for pattern on each addressed line. If pattern addresses are used, the pattern // represents the last pattern address specified. The following flags can be specified:

n

Replace nth instance of / pattern / on each addressed line. n is any number in the range 1 to 512; the default is 1.

g

Replace all instances of / pattern / on each addressed line, not just the first instance.

I

Case insensitive match. This flag is available only on GNU versions of sed.

p

Print the line if a successful substitution is done. If several successful substitutions are done, multiple copies of the line will be printed.

w file

Write the line to a file if a replacement was done.

Examples

Here are some short, commented scripts:

                  # Change third and fourth quote to ( and ):
/function/{
                  s/"/(/3
                  s/"/)/4
                  }

                  # Remove all quotes on a given line:
/Title/s/"//g

                  # Remove first colon or all quotes; print resulting lines:
s/://p
                  s/"//gp

                  # Change first "if" but leave "ifdef" alone:
/ifdef/!s/if/   if/

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required