Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

Remove leading & trailing whitespace from a Bash variable (See related posts)

# Taken from: http://www.jlaforums.com/viewtopic.php?t=1427403
# Author: Chris F.A. Johnson

var='   space test   '
echo $var | sed -n -e 'l'
echo "$var" | sed -n -e 'l'

printf "%s" "${var#"${var%%[![:space:]]*}"}" | sed -n -e 'l'
printf "%s" "${var%"${var##*[![:space:]]}"}" | sed -n -e 'l'


# Space characters include: tab, newline, vertical tab, form feed, carriage return, and space.
# cf. "POSIX character classes" at http://en.wikipedia.org/wiki/Regular_expression

var="${var#"${var%%[![:space:]]*}"}"   # remove leading whitespace characters
var="${var%"${var##*[![:space:]]}"}"   # remove trailing whitespace characters

echo "$var" | sed -n -e 'l'

You need to create an account or log in to post comments to this site.