A few more string functions to fill up your toolbox.
When you need to make sure a string is only a certain number of characters long, you might need to truncate it.
trunc() {
local str="$1"
local len="$2"
if [ "${#str}" -gt "$len" ]; then
echo "${str:0:$len}"
else
echo "$str"
fi
}
Usage:
myLongstr="primis a fringilla erat maximus " HowLong=17 myShortstr=$(trunc "$myLongstr" 17) echo "\$myLongstr : -->$myLongstr<--" echo "\$myShortstr: '-->$myShortstr'<--"
Note that this removes (truncates) from the END of the string.
Convert a string all upper-case
uppercase() {
echo "$1" | tr '[:lower:]' '[:upper:]'
}
Usage:
myStr="The use of double quotation marks will help eliminate unnecessary word wrapping, word splitting, and whitespace when variable values contain a separator character or whitespace." myStrUp=$(uppercase "$myStr") echo "\$myStrUp: $myStrUp"
Of course we also might need the opposite ...
lowercase() {
echo "$1" | tr '[:upper:]' '[:lower:]'
}
Usage:
myStrUp: THE USE OF DOUBLE QUOTATION MARKS WILL HELP ELIMINATE UNNECESSARY WORD WRAPPING, WORD SPLITTING, AND WHITESPACE WHEN VARIABLE VALUES CONTAIN A SEPARATOR CHARACTER OR WHITESPACE.
myStrLow=$(lowercase "$myStrUp") echo "\$myStrUp: $myStrUp" echo "\$myStrLow: $myStrLow"
In these past few function pages, we've used a few new commands (awk, sed, tr, grep).
Use the resources link to find out more about them.
We also introduced some funky regular expression classes so we should explain more about that.
Regex Classes