How to remove space from string? [duplicate]

In ubuntu bash script how to remove space from one variable

string will be

   3918912k 

Want to remove all blank space.


Solution 1:

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

Solution 2:

Try doing this in a shell:

var="  3918912k"
echo ${var//[[:blank:]]/}

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