O'Reilly logo

Linux Shell Scripting Cookbook by Sarath Lakshman

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

Replacing strings from a text or file

String replacement is a frequently-used text-processing task. It can be done easily with regular expressions by matching the required text.

Getting ready

When we hear the term 'replace', every system admin will recall sed. sed is the universal tool under UNIX-like systems to make replacements in text or in a file. Let's see how to do it.

How to do it...

The sed primer recipe contains most of the usages of sed. You can replace a string or pattern as follows:

$ sed 's/PATTERN/replace_text/g' filename

Or:

$ stdin | sed 's/PATTERN/replace_text/g'

We can also use double quote (") instead of single quote ('). When double quote (") is used, we can specify variables inside the sed pattern and replacement strings. For ...

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