Text slicing and parameter operations
This recipe walks through some simple text-replacement techniques and parameter-expansion shorthands available in Bash. A few simple techniques can help avoid writing multiple lines of code.
How to do it...
Let's get into the tasks.
Replace some text from a variable:
$ var="This is a line of text" $ echo ${var/line/REPLACED} This is a REPLACED of text"
The line
word is replaced with REPLACED
.
We can produce a substring by specifying the start position and string length, using the following syntax:
${variable_name:start_position:length}
Print from the fifth character onwards:
$ string=abcdefghijklmnopqrstuvwxyz $ echo ${string:4} efghijklmnopqrstuvwxyz
Print eight characters starting from the fifth character:
$ echo ${string:4:8} efghijkl
The first character in a string is at position 0
. We can count from the last letter as -1
. When -1
is inside a parenthesis, (-1)
is the index for the last letter:
echo ${string:(-1)} z $ echo ${string...