如何从 Bash 中的字符串中删除前导空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32753054/
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
How to remove leading whitespace from a string in Bash
提问by Shawon0418
For example, I have a string, " some string", and I want to put "some string" in another string variable. How do I do that?
例如,我有一个字符串“某个字符串”,我想将“某个字符串”放入另一个字符串变量中。我怎么做?
My code:
我的代码:
function get_title() {
t1=$(get_type "")
t2="ACM Transactions"
t3="ELSEVIER"
t4="IEEE Transactions"
t5="MIT Press"
if [ "$t1"=="$t2" ];
then
title=$(less "" | head -1)
elif [ "$t1"=="$t5" ];
then
title=$(less "" | head -3)
fi
echo "$title"
}
As you can see the $title can return unwanted whitespace in front of text in center aligned texts. I want to prevent that.
如您所见, $title 可以在居中对齐的文本中返回文本前不需要的空白。我想阻止这种情况。
回答by peak
A robust and straightforward approach is to use sede.g.
一个健壮而直接的方法是使用sed例如
$ sed 's/^[[:space:]]*//' <<< "$var"
If you are willing to turn on extended globbing (shopt -s extglob), then the following will remove initial whitespace from $var:
如果您愿意打开扩展 globbing ( shopt -s extglob),那么以下内容将从 $var 中删除初始空格:
"${var##+([[:space:]])}"
Example:
例子:
var=$' \t abc \t ' echo "=${var##+([[:space:]])}="
=abc =