Bash Snippet: Trim Function

Occasionally I find myself wanting to removing leading and/or trailing occurrences of a character or string from a larger string in bash. A couple common uses are removing quotes, or stripping an unknown number of spaces leading into the data of interest. This can be done pretty easily with other methods such as awk or sed, but with the disadvantage of requiring external commands. This a pure bash implementation using only shell built-ins. It might be better to rewrite this with $BASH_REMATCH, but this is what I currently have.

#!/bin/bash

trim () {
    str="$1"
    match="$2"
    # trim spaces by default
    if [ -z "$match" ]; then
        match=" "
    fi
    # trim leading
    while [ "${str:0:${#match}}" == "$match" ];
    do
        str="${str:${#match}:${#str}}"
    done
    # trim tailing
    while [ "${str:$((${#str}-${#match}))}" == "$match" ];
    do
        str="${str:0:$((${#str} - ${#match}))}"
    done
    echo "$str"
}

#Remove leading and trailing spaces
example="    Hello     "
echo "`trim  "$example" " "`"

#The second parameter is optional when removing spaces
example="    Hello     "
echo "`trim  "$example"`"


#Remove leading and trailing occurences of "word"
example="wordHelloword"
echo "`trim  "$example" "word"`"
This entry was posted in Bash. Bookmark the permalink.

One Response to Bash Snippet: Trim Function

  1. Chris says:

    This deserves a look

    http://codesnippets.joyent.com/posts/show/1816

    Much cleaner solution for removing leading and trailing whitespace, but I wasn’t having luck with getting it to remove character strings without sometimes clobbering the meat of my variable. Probably worth sitting down to make sense out of.

Leave a Reply

Your email address will not be published. Required fields are marked *