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
To print eight characters starting from the fifth character, use the following command:
$ echo ${string:4:8} efghijkl
The index is specified by counting the start letter as 0
. We can also specify counting from the last letter as -1
. It...