10

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?

Community
  • 1
  • 1
Bharat Sinha
  • 13,973
  • 6
  • 39
  • 63

2 Answers2

19

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
Gene Pavlovsky
  • 1,515
  • 17
  • 14
jpmuc
  • 1,092
  • 14
  • 30
1

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

kent$  echo "    foo  -  -  -  bar   "|awk '{sub(/^ */,"",$0);sub(/ *$/,"",$0)}1'
foo  -  -  -  bar
Kent
  • 189,393
  • 32
  • 233
  • 301