【问题标题】:How to iterate over two strings simultaneously ksh如何同时迭代两个字符串ksh
【发布时间】:2017-08-04 16:36:34
【问题描述】:

我正在使用其他人的 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

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

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

【问题讨论】:

  • korn shell 中的数组条目数有限,但对于这种类型的需求来说很方便。除了使用 awk 或其他工具外,我只能想到长度相等的数组并对其进行迭代。

标签: ksh


【解决方案1】:

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

`#!/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
`

【讨论】:

    【解决方案2】:

    与其他 cmets 一样,不确定为什么无法使用数组,尤其是如果您计划稍后在代码中多次引用单个元素。

    假设您希望将 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
    ++++++++++
    

    【讨论】:

      猜你喜欢
      • 2019-07-15
      • 2023-01-12
      • 2013-04-30
      • 2015-03-09
      • 2010-10-24
      • 2020-11-12
      • 1970-01-01
      • 2017-06-18
      • 2015-05-26
      相关资源
      最近更新 更多