Table of Contents
BASH - Get a SubString
Format
${var:start_position:length}
or
${var:start_position -length}
or
${var: -start_position -length}
or
${var: -start_position:length}
Return every character
var="abcdefgh" echo ${#var:0}
returns:
abcdefgh
NOTE: A starting position of 0 this means start at the begin; and therefore returns everything.
Return a substring from a specific position
var="abcdefgh" echo ${#var:3}
returns:
defgh
NOTE: This 3 specifies to start from position 3.
Return a substring between a string
var="abcdefgh" echo ${#var:3:2}
returns:
de
NOTE: This starts at position 3; and then returns the next 2 characters.
Return a substring from beginning of a string
var="abcdefgh" echo ${#var:0:2}
returns:
ab
NOTE: This starts at position 0; and then returns the next 2 characters.
Return last few characters from back of a string
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.
Return a substring from back of a string
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.
Substrings with Concatenation
var="abcdefgh" echo ${var:0:(-1 -4)}XYZ
returns:
abcXYZ
Extracting Substrings Using Cut
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