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

SiB*_*SiB 9 unix bash shell

可能重复:
如何从bash变量中修剪空格?

我搜索并尝试了一些解决方案,但似乎没有什么对我有用......

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

jpm*_*muc 16

我可以想到两个选择:

variable="  gfgergj lkjgrg  "
echo $variable | sed 's,^ *,,; s, *$,,'
Run Code Online (Sandbox Code Playgroud)

要不然

nospaces=${variable## } # remove leading spaces
nospaces=${variable%% } # remove trailing spaces
Run Code Online (Sandbox Code Playgroud)

  • nospaces = $ {variable //}删除所有空格 (5认同)
  • `nospaces = $ {variable //}`实际上删除了Bash中的前导和尾随空格 (2认同)
  • nospaces=${variable// } 删除所有空格 (2认同)