当前位置 博文首页 > shell 判断字符串是否存在数组中的实现示例

    shell 判断字符串是否存在数组中的实现示例

    作者:幸福丶如此 时间:2021-01-31 18:10

    语法格式: [[ "${array[@]}" =~ "字符串" ]]

    示例:

    #!/bin/sh
    ##数组
    array=(
    address
    base
    cart
    company
    store
    )
    
     
    # $1 如果存在,输出 $1 exists,$1 如果不存在,输出 $1 not exists
    if [ "$1" != null ];then
     if [[ "${array[@]}" =~ "${1}" ]]; then
     echo "$1 exists"
     elif [[ ! "${array[@]}" =~ "${1}" ]]; then
     echo "$1 not exists"
     fi
    else
     echo "请传入一个参数"
    fi

    扩展:

    这种方式不仅可以判断字符串是否存在数组中,也快判断字符串是否存在一个文本中。

    ## 判断字符串是否存在文本中
    #!/bin/sh
    
    names="This is a computer , I am playing games in the computer"
    if [[ "${names[@]}" =~ "playing" ]]; then
     echo '字符串存在'
    fi
    

    shell将字符串分隔成数组

    #!/bin/bash
    a="hello,world,nice,to,meet,you"
    #要将$a分割开,先存储旧的分隔符
    OLD_IFS="$IFS"
    
    #设置分隔符
    IFS="," 
    
    #如下会自动分隔
    arr=($a)
    
    #恢复原来的分隔符
    IFS="$OLD_IFS"
    
    #遍历数组
    for s in ${arr[@]}
    do
    echo "$s"
    done

    变量$IFS存储着分隔符,这里我们将其设为逗号 "," OLD_IFS用于备份默认的分隔符,使用完后将之恢复默认。
    arr=($a)用于将字符串$a按IFS分隔符分割到数组$arr
    ${arr[0]} ${arr[1]} ... 分别存储分割后的数组第1 2 ... 项
    ${arr[@]}存储整个数组。
    ${!arr[@]}存储整个索引值:1 2 3 4 ...
    ${#arr[@]} 获取数组的长度。

    js
    下一篇:没有了