Bash Trim Whitespace

Tags: May 2, 2014 10:45 AM

To remove leading and trailing whitespace from a subset of strings in a shell we can use sed.

$ echo '   #FOO#   ' | sed -e 's/\s*$//' -e 's/^\s*//'
#FOO#

Function 'trim'

To reuse it in another place, it is good idea to wrap it as a function.
# Function to trim leading and trailing spaces
trim() {
  # Accept input from argument or STDIN
  # So you can do both:
  # $ echo '  #FOO#   ' | trim
  # or
  # $ trim '   #FOO#   '
  local STRING=$( [ ! -z "$1" ] && echo $1 || cat ; )
  
  echo "$STRING" | sed -e 's/^\s*//' -e 's/\s*$//'
}
Now it can be used to trim a string both from argument or standard input.
$ echo '   #FOO#   ' | trim
#FOO#

$ trim '   #FOO#   '
#FOO#

Reference

Share on Facebook Twitter

0 comments:

Post a Comment