Strip
The purpose of this document is to show how to strip whitespace.
echo " test test test " | tr -d ' '
'testtesttest'
(removes all spaces)
echo " test test test " | sed 's/ *$//g'
' test test test'
(removes trailing)
echo " test test test " | sed 's/^ *//g'
'test test test '
(removes leading)
echo " test test test " | sed -e 's/^ *//g' -e 's/ *$//g'
'test test test'
(removes leading and trailing)
trimmed=$([[ " test test test " =~ [[:space:]]*([^[:space:]]|[^[:space:]].*[^[:space:]])[[:space:]]* ]]; echo -n "${BASH_REMATCH[1]}")
removes leading and trailing whitespace (not just spaces)
A complex, working trim() function
trim() { # Determine if 'extglob' is currently on. local extglobWasOff=1 shopt extglob >/dev/null && extglobWasOff=0 (( extglobWasOff )) && shopt -s extglob # Turn 'extglob' on, if currently turned off. # Trim leading and trailing whitespace local var=$1 var=${var##+([[:space:]])} var=${var%%+([[:space:]])} (( extglobWasOff )) && shopt -u extglob # If 'extglob' was off before, turn it back off. echo -n "$var" # Output trimmed string. } # Usage string=" abc def ghi "; #need to quote input-string to preserve internal white-space if any trimmed=$(trim "$string"); echo "$trimmed";
A simplified trim() function
# Trim whitespace from both ends of specified parameter trim() { read -rd '' $1 <<<"${!1}" } # Unit test for trim() test_trim() { local foo="$1" trim foo test "$foo" = "$2" } test_trim hey hey && test_trim ' hey' hey && test_trim 'ho ' ho && test_trim 'hey ho' 'hey ho' && test_trim ' hey ho ' 'hey ho' && test_trim $'\n\n\t hey\n\t ho \t\n' $'hey\n\t ho' && test_trim $'\n' '' && test_trim '\n' '\n' && echo passed
Nice version
trim() { trimmed=$1 trimmed=${trimmed%% } trimmed=${trimmed## } echo $trimmed } HELLO_WORLD=$(trim "hello world ") FOO_BAR=$(trim " foo bar") BOTH_SIDES=$(trim " both sides ") echo "'${HELLO_WORLD}', '${FOO_BAR}', '${BOTH_SIDES}'"