如何同时遍历两个字符串ksh

How to iterate over two strings simultaneously ksh

我正在使用由另一个人的 ksh93 脚本以打印格式返回到标准输出的数据。根据我给它的标志,他们的脚本会为我提供我的代码所需的信息。它就像一个由空格分隔的列表,这样程序的 运行 格式为:

"1 3 4 7 8"
"First Third Fourth Seventh Eighth"

对于我正在做的工作,我需要能够匹配每个输出的条目,以便我可以按以下格式打印信息:

1:First
3:Third
4:Fourth
7:Seventh
8:Eighth

我需要做的不仅仅是打印数据,我只需要能够访问每个字符串中的信息对。即使字符串的实际内容可以是任意数量的值,我从另一个脚本 运行 获得的两个字符串将始终具有相同的长度。

我想知道是否存在同时迭代两者的方法,大致如下:

str_1=$(other_script -f)
str_2=$(other_script -i)
for a,b in ${str_1},${str_2} ; do
  print "${a}:${b}"
done

这显然不是正确的语法,但我一直无法找到使其工作的方法。有没有办法同时遍历两者?

我知道我可以先将它们转换为数组,然后按数字元素进行迭代,但如果有办法同时对两者进行迭代,我想节省转换它们的时间。

为什么你认为将字符串转换为数组不快?
例如:

`#!/bin/ksh93

set -u
set -A line1 
string1="1 3 4 7 8"
line1+=( ${string1} )

set -A line2 
string2="First Third Fourth Seventh Eighth"
line2+=( ${string2})

typeset -i num_elem_line1=${#line1[@]}
typeset -i num_elem_line2=${#line2[@]}

typeset -i loop_counter=0

if (( num_elem_line1 == num_elem_line2 ))
then 
   while (( loop_counter < num_elem_line1 ))
   do
       print "${line1[${loop_counter}]}:${line2[${loop_counter}]}"
       (( loop_counter += 1 ))
  done
fi
`

与其他评论一样,不确定为什么数组是不可能的,特别是如果您计划稍后在代码中多次引用单个元素。

假设您希望将 str_1/str_2 变量维护为字符串的示例脚本;我们将加载到数组中以引用单个元素:

$ cat testme
#!/bin/ksh

str_1="1 3 4 7 8"
str_2="First Third Fourth Seventh Eighth"

str1=( ${str_1} )
str2=( ${str_2} )

# at this point matching array elements have the same index (0..4) ...

echo "++++++++++ str1[index]=element"

for i in "${!str1[@]}"
do
    echo "str1[${i}]=${str1[${i}]}"
done

echo "++++++++++ str2[index]=element"

for i in "${!str1[@]}"
do
    echo "str2[${i}]=${str2[${i}]}"
done

# since matching array elements have the same index, we just need
# to loop through one set of indexes to allow us to access matching
# array elements at the same time ...

echo "++++++++++ str1:str2"

for i in "${!str1[@]}"
do
    echo ${str1[${i}]}:${str2[${i}]}
done

echo "++++++++++"

还有一个运行的脚本:

$ testme
++++++++++ str1[index]=element
str1[0]=1
str1[1]=3
str1[2]=4
str1[3]=7
str1[4]=8
++++++++++ str2[index]=element
str2[0]=First
str2[1]=Third
str2[2]=Fourth
str2[3]=Seventh
str2[4]=Eighth
++++++++++ str1:str2
1:First
3:Third
4:Fourth
7:Seventh
8:Eighth
++++++++++