检查变量是否以 bash 中的另一个变量开头



与此类似>> 在 bash 中,如何检查字符串是否以某个值开头?,但不重复。

我有两个数组,对于第一个数组中的每个字符串,我想检查第二个数组中的字符串是否以第一个数组中的字符串开头。

array1=("test1","test2","test3");
array2=("test1 etc","test1 nanana","test2 zzz","test3 abracadabra");
for i in "${!array1[@]}"; do
  for j in "${!array2[@]}"; do 
    if [[ "${array1[i]}" == "${array2[j]}*" ]]; then  
      echo "array1[$i] and arry2[$j] initial matches!";
      fi; 
    done; 
done

我在里面尝试了很多条件,例如:

if [[ "${array1[i]}" == "${array2[j]*}" ]]
if [[ "${array1[i]}" == "${array2[j]}*" ]]
if [[ "${array1[i]}" = "${array2[j]*}" ]]
if [[ "${array1[i]}" = "${array2[j]}*" ]]

也没有引号、大括号等,都没有成功。

你的代码中有一些错误,首先是 bash 中的数组声明:如果你不放空格,你只有一个元素。请记住,在对变量进行任何其他操作之前,请始终打印变量。来自 bash 文档:

数组=(值 1 值 2 ...值 N(

然后,每个值采用 [indexnumber=] 字符串的形式。索引 数字是可选的。如果提供了索引,则将该索引分配给它; 否则,分配的元素的索引是最后一个元素的编号 已分配的索引加 1。声明接受此格式 也。如果未提供索引号,则索引从零开始。

循环数组元素:

for element in "${array[@]}"
do
    echo "$element"
done

下面是一个代码片段:

array1=(test1 test2 test3);
array2=(test1 etc "test1 nanana" test2zzz test3 abracadabra);
for word1 in "${array1[@]}"; do
    for word2 in "${array2[@]}"; do 
        echo "w1=$word1, w2=$word2"
        if [[ ${word2} == ${word1}* ]]; then   
            echo "$word1 and $word2 initial matches!";
        fi;                   
    done;                         
done 

在OP的评论之后,我意识到他正在尝试使用索引,为此,您还必须对索引"i"和"j"使用"$"。这是一个可行的解决方案:

for i in "${!array1[@]}"; do
    for j in "${!array2[@]}"; do    
        echo "${array1[$i]} ${array2[$j]}"
        if [[ ${array2[$j]} == ${array1[$i]}* ]]; then
            echo "$array1[$i] and $array2[$j] initial matches!";
        fi; 
    done; 
done

最新更新