对于给定的脚本,我可以提供一个具有以下形式的参数: -u [数] [信] [...]
示例:-u2T34T120F -u1T2T10F
字母为T或F,数字为整数,最多可达999。
我想要一个写循环,其中在每次迭代中,数字存储在变量“a”中,相应的字母存储在变量“b”中。循环遍历参数中的所有数字对。
对于第一个例子,参数为 -u2T34T120F ,迭代次数为:
循环结束
欢迎提出任何建议。
答案 0 :(得分:4)
这是GNU awk的一种方法:
<<<"2T34T120F" \
awk -v RS='[TF]' 'NF { printf "a: %3d b: %s\n", $0, RT }'
输出:
a: 2 b: T
a: 34 b: T
a: 120 b: F
要在bash while循环中使用它,请执行以下操作:
<<<"2T34T120F" \
awk 'NF { print $0, RT }' RS='[TF]' |
while read a b; do
echo Do something with $a and $b
done
输出:
Do something with 2 and T
Do something with 34 and T
Do something with 120 and F
答案 1 :(得分:3)
$ var='-u2T34T120F'
$ a=($(grep -o '[0-9]*' <<< "$var"))
$ b=($(grep -o '[TF]' <<< "$var"))
$ echo ${a[0]} ${a[1]} ${a[2]}
2 34 120
$ echo ${b[0]} ${b[1]} ${b[2]}
T T F
答案 2 :(得分:2)
您可以在bash中使用参数扩展:
#! /bin/bash
set -- -u2T34T120F # Set the $1.
string=${1#-u} # Remove "-u".
while [[ $string ]] ; do
a=${string%%[FT]*} # Everything before the first F or T.
string=${string#$a} # Remove the $a from the beginning of the string.
b=${string%%[0-9]*} # Everything before the first number.
string=${string#$b} # Remove the $b from the beginning of the string.
echo $a $b
done
或者,使用相同的技术,但使用数组:
a=(${string//[TF]/ }) # Remove letters.
b=(${string//[0-9]/ }) # Remove numbers.
for (( i=0; i<${#a[@]}; i++ )) ; do
echo ${a[i]} ${b[i]}
done
答案 3 :(得分:2)
怎么样:
kent$ while IFS=' ' read a b; do echo "we have a:$a,b:$b\n---"; done<<< $(echo '-u2T34T120F'|sed 's/^-u//;s/[TF]/ &\n/g')
we have a:2,b:T
---
we have a:34,b:T
---
we have a:120,b:F
---
清晰版:
while IFS=' ' read a b
do
echo "we have a:$a,b:$b\n---";
done<<< $(echo '-u2T34T120F'|sed 's/^-u//;s/[TF]/ &\n/g')