How to remove extra spaces in bash?

Charlie picture Charlie · Oct 26, 2012 · Viewed 51.4k times · Source

How to remove extra spaces in variable HEAD?

HEAD="    how to  remove    extra        spaces                     "

Result:

how to remove extra spaces

Answer

jman picture jman · Oct 26, 2012

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## }