11

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?

0

2 Answers 2

21

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
Sign up to request clarification or add additional context in comments.

4 Comments

nospaces=${variable// } actually removes leading and trailing spaces in my Bash
nospaces=${variable// } removes all spaces
nospaces=${variable// } removes all spaces
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.
1

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.