Checking if variable starts with another variable in bash
类似于bash中的这个>>,如何检查字符串是否以某个值开头?,但不重复。
我有两个数组,对于第一个数组中的每个字符串,我想检查第二个数组中的字符串是否从第一个数组开始。
1 2 3 4 5 6 7 8 9 10 | 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 |
我尝试了很多条件,比如:
1 2 3 4 | if [["${array1[i]}" =="${array2[j]*}" ]] if [["${array1[i]}" =="${array2[j]}*" ]] if [["${array1[i]}" ="${array2[j]*}" ]] if [["${array1[i]}" ="${array2[j]}*" ]] |
也没有引号、大括号等,都没有成功。
代码中有一些错误,首先是bash中的数组声明:如果不放置空格,则只有一个元素。记住,在对变量进行其他操作之前,一定要先打印这些变量。从bash文档中:
ARRAY=(value1 value2 ... valueN)
Each value is then in the form of [indexnumber=]string. The index
number is optional. If it is supplied, that index is assigned to it;
otherwise the index of the element assigned is the number of the last
index that was assigned, plus one. This format is accepted by declare
as well. If no index numbers are supplied, indexing starts at zero.
循环数组元素:
1 2 3 4 | for element in"${array[@]}" do echo"$element" done |
以下是代码段:
1 2 3 4 5 6 7 8 9 10 | 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"。以下是一个有效的解决方案:
1 2 3 4 5 6 7 8 | 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 |