Text slicing and parameter operations

This recipe walks through some of the simple text-replacement techniques and parameter-expansion shorthands 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 substring by specifying the start position and string length, by using the following syntax:

${variable_name:start_position:length}

To print from the fifth character onwards, use the following command:

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

Get Linux Shell Scripting Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.