bash 从bash变量中删除空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/324167/
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
remove whitespace from bash variable
提问by MCS
Assuming a variable contains spaces, newlines, and tabs followed by some text, why does this:
假设一个变量包含空格、换行符和制表符,后跟一些文本,为什么会这样:
${var#"${var%%[![:space:]]*}"} # strip var of everything
# but whitespace
# then remove what's left
# (i.e. the whitespace) from var
remove the white space and leave the text, but this:
删除空格并保留文本,但是:
${var##[:space:]*} # strip all whitespace from var
does not?
才不是?
回答by flolo
If I set var=" This is a test "
, both your suggestions do not work;
just the leading stuff is removed.
Why not use the replace functionality that removes all occurrences of whitespace and not just the first:
如果我设置了var=" This is a test "
,你的两个建议都不起作用;只是删除了主要内容。为什么不使用替换功能来删除所有出现的空格,而不仅仅是第一个:
${var//[[:space:]]}
回答by Barry Kelly
[:space:] is a character class. It's only valid if it is nested inside another set of [ ].
[:space:] 是一个字符类。仅当它嵌套在另一组 [] 中时才有效。
回答by converter42
flolo's answer is documented in the "Parameter Substitution" section of the bash man page. Another source of documentation is the Parameter Substitutionsection of the Advanced Bash-Scripting Guide. The ABS guide includes basic documentation with excellent example code.
flolo 的答案记录在 bash 手册页的“参数替换”部分。另一个文档来源是Advanced Bash-Scripting Guide的Parameter Substitution部分。ABS 指南包括带有优秀示例代码的基本文档。
回答by Bryant Hansen
What about $(echo $var)
$(echo $var) 怎么样
> a=" 123 456 " ; a2="$(echo $a)" ; echo "a=\"${a}\" a2=\"${a2}\""
a=" 123 456 " a2="123 456"