简体   繁体   English

两个bash数组中的模式匹配

[英]pattern matching within two bash arrays

I found quite a few posts on this but couldn't put together the pieces to solve my issue. 我发现了很多关于此的帖子,但无法拼凑起来解决我的问题。 So say I have two arrays: 所以说我有两个数组:

array1=( adir bdir anicedir )
array2=( adir anice )

I would like to have a third array like so 我想有这样的第三个数组

array3=( adir anicedir )

More specifically if the first 5 characters of the i-th element in array2 match the first 5 characters of any element in array1 then substitute array2[i] with array1[i] 更具体地说,如果array2中第i个元素的前5个字符与array1中任何元素的前5个字符相匹配,则将array2[i]替换为array1[i]

There's nothing particularly short, because bash isn't a data-processing language. 没有什么特别简短的内容,因为bash不是一种数据处理语言。 You need to use a loop. 您需要使用循环。

array1=( adir bdir anicedir )
array2=( adir anice )
array3=()

for val2 in "${array2[@]}"; do
    for val1 in "${array1[@]}"; do
        if [[ ${val1:0:5} == "${val2:0:5}" ]]; then
            array3+=("$val1")
            break
        fi
    done
done

Quoting the right-hand side of == ensures that literal string comparison, not pattern matching, is performed. 引用==的右侧可确保执行文字字符串比较而不是模式匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM