Trim the Whitespace Characters From a Bash Variable

In Bash, you can trim whitespace characters from a variable using various methods, as shown in your code. Here’s a breakdown of the different approaches:

  1. Remove Leading and Trailing White Spaces:

    1
    2
    
    NEW_VARIABLE="$(echo -e "${VARIABLE_NAME}" | tr -d '[:space:]')"
    # NEW_VARIABLE='aaa  bbb'

    This method uses the tr command to delete all whitespace characters, both leading and trailing, in the variable VARIABLE_NAME.

  2. Remove Only Leading White Spaces:

    1
    2
    
    NEW_VARIABLE="$(echo -e "${VARIABLE_NAME}" | sed -e 's/^[[:space:]]*//')"
    # NEW_VARIABLE='aaa  bbb  '

    Here, sed is used to remove only the leading whitespace characters from the variable.

  3. Remove Only Trailing White Spaces:

    1
    2
    
    NEW_VARIABLE="$(echo -e "${VARIABLE_NAME}" | sed -e 's/[[:space:]]*$//')"
    # NEW_VARIABLE='  aaa  bbb'

    This approach utilizes sed to eliminate trailing whitespace characters from the variable.

  4. Remove All White Spaces (Leading, Trailing, and Inside):

    1
    2
    
    NEW_VARIABLE="$(echo -e "${VARIABLE_NAME}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
    # NEW_VARIABLE='aaabbb'

    Here, sed is used twice. The first expression removes leading whitespaces, and the second one removes trailing whitespaces, effectively removing all whitespaces, including those inside the variable.

These methods provide flexibility depending on your specific requirements for whitespace removal in Bash.

0%