如何 trim 变量中字符串值的前导和尾随空格?
How to trim leading and trailing whitespaces from a string value in a variable?
我知道这个问题已经存在重复:How to trim whitespace from a Bash variable?。
我阅读了那里的所有答案,但我对另一个解决方案有疑问,我想知道这是否有效。
这是我认为可行的解决方案。
a=$(printf "%s" $a)
这里有一个演示。
$ a=" foo "
$ a=$(printf "%s" $a)
$ echo "$a"
foo
- 是否存在此解决方案可能失败的情况?
- 如果存在此解决方案可能失败的场景,我们能否修改此解决方案以处理该场景,同时又不会过多地损害解决方案的简单性?
如果变量 a 的开头设置为“-e”、“-n”之类的内容(取决于您稍后处理结果的方式),用户可能会使您的脚本崩溃:
-e 选项允许 echo 解释反斜杠的东西。
即使在您只想显示变量 a 的情况下,-n 也会破坏您的布局。
您可以考虑使用正则表达式来检查您的变量是否以“-”开头并后跟可用的回显选项之一(-n、-e、-E、--help、--version)。
当输入包含非空白字符之间的空格时失败。
$ a=" foo bar "
$ a=$(printf "%s" $a)
$ echo "$a"
foobar
预期的输出如下。
foo bar
您可以使用 Bash 的内置模式替换。
注意:Bash 模式替换使用 'Pathname Expansion' (glob) 模式匹配,而不是正则表达式。我的解决方案需要启用可选的 shell 行为 extglob (shopt -s extglob)。
$shopt -s extglob
$ a=" foo bar "
$ echo "Remove trailing spaces: '${a/%*([[:space:]])}'"
Remove trailing spaces: ' foo bar'
$ echo "Remove leading spaces: '${a/#*([[:space:]])}'"
Remove leading spaces: 'foo bar '
$ echo "Remove all spaces anywhere: '${a//[[:space:]]}'"
Remove all spaces anywhere: 'foobar'
有关参考,请参阅 Bash 手册页扩展部分的 'Parameter Expansion'(模式替换)和 'Pathname Expansion' 小节。
我知道这个问题已经存在重复:How to trim whitespace from a Bash variable?。
我阅读了那里的所有答案,但我对另一个解决方案有疑问,我想知道这是否有效。
这是我认为可行的解决方案。
a=$(printf "%s" $a)
这里有一个演示。
$ a=" foo "
$ a=$(printf "%s" $a)
$ echo "$a"
foo
- 是否存在此解决方案可能失败的情况?
- 如果存在此解决方案可能失败的场景,我们能否修改此解决方案以处理该场景,同时又不会过多地损害解决方案的简单性?
如果变量 a 的开头设置为“-e”、“-n”之类的内容(取决于您稍后处理结果的方式),用户可能会使您的脚本崩溃: -e 选项允许 echo 解释反斜杠的东西。
即使在您只想显示变量 a 的情况下,-n 也会破坏您的布局。
您可以考虑使用正则表达式来检查您的变量是否以“-”开头并后跟可用的回显选项之一(-n、-e、-E、--help、--version)。
当输入包含非空白字符之间的空格时失败。
$ a=" foo bar "
$ a=$(printf "%s" $a)
$ echo "$a"
foobar
预期的输出如下。
foo bar
您可以使用 Bash 的内置模式替换。 注意:Bash 模式替换使用 'Pathname Expansion' (glob) 模式匹配,而不是正则表达式。我的解决方案需要启用可选的 shell 行为 extglob (shopt -s extglob)。
$shopt -s extglob
$ a=" foo bar "
$ echo "Remove trailing spaces: '${a/%*([[:space:]])}'"
Remove trailing spaces: ' foo bar'
$ echo "Remove leading spaces: '${a/#*([[:space:]])}'"
Remove leading spaces: 'foo bar '
$ echo "Remove all spaces anywhere: '${a//[[:space:]]}'"
Remove all spaces anywhere: 'foobar'
有关参考,请参阅 Bash 手册页扩展部分的 'Parameter Expansion'(模式替换)和 'Pathname Expansion' 小节。