trim string bash code example

Example 1: bash strip preceeding white space

# Basic syntax:
sed 's/^ *//g'

# Example usage:
echo '                    text' # Printing without sed command
-->                     text
echo '                    text' | sed 's/^ *//g' # Pipe to sed command
--> text

Example 2: shell trim

STR="${STR//(^[ ]+|[ ]+$)/}"

# ${STR//--regex--/--replacement--} = replace all
# ${STR/--regex--/--replacement--} = replace one
# ^[ ]+ = empty character([ ])s(+) at the start(^) of the string
# [ ]+$ = empty character([ ])s(+) at the end($) of the string
# (A|B) = A or B