Trimming strings in BASH
Thu 17 May 2012I recently needed to trim the last N characters from a string in shell.
I wrote this little function to handle the task.
This requires a newer distro that has updated coreutils that includes
the 'fold' command (Feb 2010).
#!/bin/bash
function trimChars() {
if [ $2 ]; then
TRIM_LAST=$2
elif ! [ $2 ]; then
TRIM_LAST=4
fi
if [ $1 ]; then
STRING="$1"
elif ! [ $1 ]; then
STRING="FooBar.xls"
fi
NEW_STRING=""
STRING_ARRAY=(`echo ${STRING} | fold -w1`)
NEW_STRLEN=$[ ${#STRING_ARRAY[*]} - ${TRIM_LAST} ]
for((i=0;i<${NEW_STRLEN};i++)); do
NEW_STRING="${NEW_STRING}${STRING_ARRAY[$i]}"
done
printf "String in:\t %s\nString out:\t%s\n" ${STRING}
${NEW_STRING}
}
msnow@host1 ~ $ > trimChars foobarbaz 2
String in: foobarbaz
String out: foobarb
Update:
My brother Luke recently found a simpler way of doing this. Always more
than 1 way to skin a cat. Some methods are obviously faster. :) Thanks
Luke!
msnow@host1 ~ $ > foo=foobarbaz
msnow@host1 ~ $ > echo ${foo:0:${#foo}-2}
foobarb