How to remove extra spaces in bash?

57,581

Solution 1

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

Solution 2

Using awk:

$ echo "$HEAD" | awk '$1=$1'
how to remove extra spaces

Solution 3

Take advantage of the word-splitting effects of not quoting your variable

$ HEAD="    how to  remove    extra        spaces                     "
$ set -- $HEAD
$ HEAD=$*
$ echo ">>>$HEAD<<<"
>>>how to remove extra spaces<<<

If you don't want to use the positional paramaters, use an array

ary=($HEAD)
HEAD=${ary[@]}
echo "$HEAD"

One dangerous side-effect of not quoting is that filename expansion will be in play. So turn it off first, and re-enable it after:

$ set -f
$ set -- $HEAD
$ set +f

Solution 4

This horse isn't quite dead yet: Let's keep beating it!*

Read into array

Other people have mentioned read, but since using unquoted expansion may cause undesirable expansions all answers using it can be regarded as more or less the same. You could do

set -f
read HEAD <<< $HEAD
set +f

or you could do

read -rd '' -a HEAD <<< "$HEAD"  # Assuming the default IFS
HEAD="${HEAD[*]}"

Extended Globbing with Parameter Expansion

$ shopt -s extglob
$ HEAD="${HEAD//+( )/ }" HEAD="${HEAD# }" HEAD="${HEAD% }"
$ printf '"%s"\n' "$HEAD"
"how to remove extra spaces"

*No horses were actually harmed – this was merely a metaphor for getting six+ diverse answers to a simple question.

Solution 5

Here's how I would do it with sed:

string='    how to  remove    extra        spaces                     '
echo "$string" | sed -e 's/  */ /g' -e 's/^ *\(.*\) *$/\1/'

=> how to remove extra spaces   # (no spaces at beginning or end)

The first sed expression replaces any groups of more than 1 space with a single space, and the second expression removes any trailing or leading spaces.

Share:
57,581
Charlie
Author by

Charlie

Updated on May 04, 2021

Comments

  • Charlie
    Charlie about 3 years

    How to remove extra spaces in variable HEAD?

    HEAD="    how to  remove    extra        spaces                     "
    

    Result:

    how to remove extra spaces