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

Text slicing and parameter operations

This recipe walks through some of the simple text replacement techniques and parameter expansion short hands available in Bash. A few simple techniques can often help us avoid having to write multiple lines of code.

How to do it...

Let's get into the tasks.

Replacing some text from a variable can be done as follows:

$ var="This is a line of text"
$ echo ${var/line/REPLACED}
This is a REPLACED of text"

line is replaced with REPLACED.

We can produce a sub-string by specifying the start position and string length, by using the following syntax:

${variable_name:start_position:length}

To print from the fifth character onward use the following command:

$ string=abcdefghijklmnopqrstuvwxyz
$ echo ${string:4}
efghijklmnopqrstuvwxyz ...

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