Echo substrings of a variable
Say you have a variable set in a shell script:
export testPath='/Users/mary/code/thingy.rb'
You can echo that variable as usual:
echo $testPath
# /Users/mary/code/thingy.rb
But you can also get substrings of that variable as you echo it, using substring extraction. The substring extraction syntax is ${variable:offset:length}
echo ${testPath:11}
# /code/thingy.rb
echo ${testPath:12:4}
# code
You can also change the prefix (${variable#prefix}
) and suffix (${variable%suffix}
):
echo ${testPath#/Users/mary/code/}
# thingy.rb
echo ${testPath%.rb}
# /Users/mary/code/thingy
Tweet