Shell脚本:如何从bash变量中修剪空格

时间:2012-08-03 07:43:48

标签: bash shell unix

  

可能重复:
  How to trim whitespace from bash variable?

我已经搜索并尝试了许多解决方案,但似乎没有什么对我有用......

我有一个shell变量,由于前导和尾随空格而导致问题。我们如何使用shell脚本删除单行中的所有空格?

2 个答案:

答案 0 :(得分:16)

我可以想到两个选择:

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

或者

nospaces=${variable## } # remove leading spaces
nospaces=${variable%% } # remove trailing spaces

答案 1 :(得分:1)

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

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