This question already has an answer here:
- How to trim whitespace from a Bash variable? 41 answers
In ubuntu bash script how to remove space from one variable
string will be
3918912k
Want to remove all blank space.
This question already has an answer here:
In ubuntu bash script how to remove space from one variable
string will be
3918912k
Want to remove all blank space.
A funny way to remove all spaces from a variable is to use printf:
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):I posted this answer just because it's funny, not to use it in practice.
The tools
sed
ortr
will do this for you by swapping the whitespace for nothingsed 's/ //g'
tr -d ' '
Example:
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.Since you're using bash, the fastest way would be:
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
:Try doing this in a shell:
That uses parameter expansion (it's a non posix feature)
[[:blank:]]
is a POSIX regex class (remove spaces, tabs...), see http://www.regular-expressions.info/posixbrackets.html