比如我有一个变量 “123 456 789”,要求以空格为分隔符把这个变量分隔,并把分隔后的字段分别赋值给变量,即a=123;b=456;c=789
共有3中方法:
法一:先定义一个数组,然后把分隔出来的字段赋值给数组中的每一个元素
法二:通过eval+赋值的方式
法三:通过多次awk把每个字段赋值
[danni@vm-bestgame-18 shell]$ cat Demo1.sh
#!/bin/bash
a="123 456"
#方法一:通过数组的方式
declare -a arr
index=0
for i in $(echo $a | awk '{print $1,\(2</span>}'</span><span class="token variable">)</span></span>
<span class="token keyword">do</span>
arr<span class="token punctuation">[</span><span class="token variable">\)index]=\(i</span>
<span class="token keyword">let</span> <span class="token string">"index+=1"</span>
<span class="token keyword">done</span>
<span class="token keyword">echo</span> <span class="token variable">\){arr[0]}
echo ${arr[1]}
# 方法二:通过eval+赋值的方式
b=""
c=""
eval $(echo $a | awk '{ printf("b=%s;c=%s",$1,\(2<span class="token variable">)</span></span><span class="token punctuation">}</span><span class="token string">')
echo <span class="token variable">\)b
方法三
m=""
n=""
m=</span><span class="token keyword">echo</span> $a <span class="token operator">|</span> <span class="token function">awk</span> <span class="token string">'{print <span class="token variable">$1</span>}'</span><span class="token variable">
n=echo <span class="token variable">$a</span> | awk '</span><span class="token punctuation">{<!-- --></span>print <span class="token variable">$2</span><span class="token punctuation">}</span>'
echo \(m</span>
<span class="token keyword">echo</span> <span class="token variable">\)n