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?

4

2 回答 2

19

我可以想到两个选择:

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

要不然

nospaces=${variable## } # remove leading spaces
nospaces=${variable%% } # remove trailing spaces
于 2012-08-03T07:50:56.167 回答
1

有很多方法可以实现这一点,awk oneliner:

kent$  echo "    foo  -  -  -  bar   "|awk '{sub(/^ */,"",$0);sub(/ *$/,"",$0)}1'
foo  -  -  -  bar
于 2012-08-03T07:54:26.073 回答