bash 如何拆分字符串并将每个拆分存储到变量中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22459129/
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 split a string and store each split into variables
提问by Dan
function check()
{
[email protected]
arr=$(echo $word | tr "@" "\n")
for x in $arr
do
echo "> $x"
done
}
for output I get
我得到的输出
name
gmail.com
I want to store each of them into separate variables. How do I do that?
我想将它们中的每一个存储到单独的变量中。我怎么做?
Do I go
我去吗
for x in $arr
do
echo "> $x"
first=$x
second=$x
done
Quite lost here. Help me out please!
在这里迷路了。请帮帮我!
回答by fedorqui 'SO stop harming'
You can use the following read
sentence, in which the @
is defined as field separator:
您可以使用以下read
句子,其中@
定义为字段分隔符:
$ var="[email protected]"
$ IFS="@" read var1 var2 <<< "$var"
Then see how the values have been stored:
然后查看值是如何存储的:
$ echo "var1=$var1, var2=$var2"
var1=name, var2=gmail.com
You can also make use of cut
:
您还可以使用cut
:
$ name=$(cut -d'@' -f1 <<< "$var")
$ email=$(cut -d'@' -f2 <<< "$var")
$ echo "name=$name, email=$email"
name=name, email=gmail.com
回答by Saucier
You could use bash parameter expansion/substring removal:
您可以使用 bash参数扩展/子字符串删除:
$ var="[email protected]"
# Remove everything from the beginning of the string until the first
# occurrence of "@"
$ var1="${var#*@}"
# Remove everything from the end of the string until the first occurrence
# of "@"
$ var2="${var%@*}"
$ echo "$var1"
gmail.com
$ echo "$var2"
name