Possible Duplicate:
How to trim whitespace from bash variable?

I have searched and attempted a number of solutions but nothing seems to work for me...

I have a shell variable which is causing issues due to leading and trailing spaces. how can we get rid of all the spaces in a single line using shell script?

share|improve this question

marked as duplicate by eckes, Jürgen Thelen, chepner, Donal Fellows, Neil Aug 4 '12 at 0:04

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

up vote 12 down vote accepted

I can think of two options:

variable="  gfgergj lkjgrg  "
echo $variable | sed 's,^ *,,; s, *$,,'

or else

nospaces=${variable## } # remove leading spaces
nospaces=${variable%% } # remove trailing spaces
share|improve this answer
1  
nospaces=${variable// } actually removes leading and trailing spaces in my Bash – Theodros Zelleke Aug 3 '12 at 9:01
5  
nospaces=${variable// } removes all spaces – Harpreet Jan 5 '14 at 21:19
1  
nospaces=${variable// } removes all spaces – gammay Apr 12 '16 at 9:25
    
The second option removes at most one space. This method is rather long, only applies to bash, but is quite efficient and can also take care of tabs, newlines etc. – Gene Pavlovsky Jul 12 '17 at 16:00

there are so many ways to achieve that, awk oneliner:

kent$  echo "    foo  -  -  -  bar   "|awk '{sub(/^ */,"",$0);sub(/ *$/,"",$0)}1'
foo  -  -  -  bar
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.