Since you're using bash, the fastest way would be:
shopt -s extglob # Allow extended globbing
var=" lakdjsf lkadsjf "
echo "${var//+([[:space:]])/}"
It's fastest because it uses built-in functions instead of firing up extra processes.
However, if you want to do it in a POSIX-compliant way, use sed
:
var=" lakdjsf lkadsjf "
echo "$var" | sed 's/[[:space:]]//g'
The tools sed
or tr
will do this for you by swapping the whitespace for nothing
sed 's/ //g'
tr -d ' '
Example:
$ echo " 3918912k " | sed 's/ //g'
3918912k
A funny way to remove all spaces from a variable is to use printf:
$ myvar='a cool variable with lots of spaces in it'
$ printf -v myvar '%s' $myvar
$ echo "$myvar"
acoolvariablewithlotsofspacesinit
It turns out it's slightly more efficient than myvar="${myvar// /}"
, but not safe regarding globs (*
) that can appear in the string. So don't use it in production code.
If you really really want to use this method and are really worried about the globbing thing (and you really should), you can use set -f
(which disables globbing altogether):
$ ls
file1 file2
$ myvar=' a cool variable with spaces and oh! no! there is a glob * in it'
$ echo "$myvar"
a cool variable with spaces and oh! no! there is a glob * in it
$ printf '%s' $myvar ; echo
acoolvariablewithspacesandoh!no!thereisaglobfile1file2init
$ # See the trouble? Let's fix it with set -f:
$ set -f
$ printf '%s' $myvar ; echo
acoolvariablewithspacesandoh!no!thereisaglob*init
$ # Since we like globbing, we unset the f option:
$ set +f
I posted this answer just because it's funny, not to use it in practice.
You can also use echo
to remove blank spaces, either at the beginning or at the end of the string, but also repeating spaces inside the string.
$ myVar=" kokor iiij ook "
$ echo "$myVar"
kokor iiij ook
$ myVar=`echo $myVar`
$
$ # myVar is not set to "kokor iiij ook"
$ echo "$myVar"
kokor iiij ook
Source: Stackoverflow.com