${var:start_position:length}
or
${var:start_position -length}
or
${var: -start_position -length}
or
${var: -start_position:length}
var="abcdefgh" echo ${#var:0}
returns:
abcdefgh
NOTE: A starting position of 0 this means start at the begin; and therefore returns everything.
var="abcdefgh" echo ${#var:3}
returns:
defgh
NOTE: This 3 specifies to start from position 3.
var="abcdefgh" echo ${#var:3:2}
returns:
de
NOTE: This starts at position 3; and then returns the next 2 characters.
var="abcdefgh" echo ${#var:0:2}
returns:
ab
NOTE: This starts at position 0; and then returns the next 2 characters.
var="abcdefgh" echo ${#var: -4}
returns:
efgh
NOTE: This returns the last 4 characters.
There must be a SPACE before the minus sign!
Be aware that if the length after the colon is longer than the string, then nothing is returned.
var="abcdefgh" echo ${#var -1 -3}
returns:
efgh
NOTE: This returns the last character; and 3 extra characters.
There must be a SPACE before the minus signs.
Be aware that if the length of any position is longer than the string, then nothing is returned.
var="abcdefgh" echo ${var:0:(-1 -4)}XYZ
returns:
abcXYZ
cut can be used to ‘cut’ a portion of a string, aka the substring.
#!/bin/bash Str="My name is Peter" #subStr=${Str:0:6} subStr=$(echo $Str| cut -d ' ' -f 1-3) echo $subStr