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"`"

Categories:Bash
Published on :Posted on

1 thought on “Bash Snippet: Trim Function”

·

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.

Post your comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.