Bash supports a surprising number of string manipulation operations. Unfortunately, these tools lack a unified focus. Some are a subset of parameter substitution, and others fall under the functionality of the UNIX expr command. This results in inconsistent command syntax and overlap of functionality, not to mention confusion. *
This is a short explanation of Bash’s substition mechanisms I use most
frequently. For further information visit the
Advanced Bash-Scripting Guide.
The construct ${VARIABLE%pattern}
removes the shortest possible suffix
of a variable string. This is most commonly used to remove a
filename extension
from a variable. As pattern
we use .*
= a dot (.) plus
a possible number of characters.
:~$ VARIABLE=/home/lisl/dummy.txt:~$ echo $VARIABLE /home/lisl/dummy.txt:~$ echo ${VARIABLE%.*} /home/lisl/dummy
While the construct ${VARIABLE%.*}
removes the shortest possible suffix
of the variable string, the construct ${VARIABLE%%.*}
(=2 times %
!)
removes the longest possible suffix:
:~$ ONEDOT=/home/lisl/dummy.txt :~$ TWODOT=/home/lisl/.hidden/dummy.txt:~$ echo ${ONEDOT%.*} /home/lisl/dummy:~$ echo ${ONEDOT%%.*} /home/lisl/dummy
Within this example, we get the same output, because the string contains only one dot and therefore the longest and the shortest possible suffix is actually the same. If the string contains more than one dot, you will see the difference:
:~$ echo ${TWODOT%.*} /home/lisl/.hidden/dummy:~$ echo ${TWODOT%%.*} /home/lisl/
To remove the prefix instead of the suffix you use #
instead of %
.
:~$ echo ${TWODOT#*.} hidden/dummy.txt:~$ echo ${TWODOT##*.} txt
Best way to start is just by trying out. In-depth documentation here.