I have this string stored in a variable:
(我将此字符串存储在变量中:)
IN="bla@some.com;john@home.com"
Now I would like to split the strings by ;
(现在我想用拆分字符串;
)
delimiter so that I have: (分隔符,以便我有:)
ADDR1="bla@some.com"
ADDR2="john@home.com"
I don't necessarily need the ADDR1
and ADDR2
variables.
(我不一定需要ADDR1
和ADDR2
变量。)
If they are elements of an array that's even better. (如果它们是数组的元素,那就更好了。)
After suggestions from the answers below, I ended up with the following which is what I was after:
(经过以下答案的建议后,我得出了以下结论:)
#!/usr/bin/env bash
IN="bla@some.com;john@home.com"
mails=$(echo $IN | tr ";" "
")
for addr in $mails
do
echo "> [$addr]"
done
Output:
(输出:)
> [bla@some.com]
> [john@home.com]
There was a solution involving setting Internal_field_separator (IFS) to ;
(解决方案涉及将Internal_field_separator (IFS)设置为;
)
. (。)
I am not sure what happened with that answer, how do you reset IFS
back to default? (我不确定该答案发生了什么,如何将IFS
重置为默认值?)
RE: IFS
solution, I tried this and it works, I keep the old IFS
and then restore it:
(RE: IFS
解决方案,我尝试过并且可以正常工作,我保留了旧的IFS
,然后将其还原:)
IN="bla@some.com;john@home.com"
OIFS=$IFS
IFS=';'
mails2=$IN
for x in $mails2
do
echo "> [$x]"
done
IFS=$OIFS
BTW, when I tried
(顺便说一句,当我尝试)
mails2=($IN)
I only got the first string when printing it in loop, without brackets around $IN
it works.
(在循环打印时,我只有第一个字符串,没有$IN
括弧,它可以工作。)
ask by stefanB translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…