How to remove extra spaces in bash?

bash, removing-whitespace

Solution

Try this:

echo "$HEAD" | tr -s " "

or maybe you want to save it in a variable:

NEWHEAD=$(echo "$HEAD" | tr -s " ")

Update

To remove leading and trailing whitespaces, do this:

NEWHEAD=$(echo "$HEAD" | tr -s " ")
NEWHEAD=${NEWHEAD%% }
NEWHEAD=${NEWHEAD## }

Problem

How to remove extra spaces in variable `HEAD`? ``` HEAD=" how to remove extra spaces " ``` Result: ``` how to remove extra spaces ```

Original source