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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11791402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 22:30:53  来源:igfitidea点击:

Shell Script: How to trim spaces from a bash variable

bashshellunix

提问by Bharat Sinha

Possible Duplicate:
How to trim whitespace from bash variable?

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

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?

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

回答by jpmuc

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

回答by Kent

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

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

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