您现在的位置是:网站首页> 编程资料编程资料
shell 判断字符串是否存在数组中的实现示例_linux shell_
2023-05-26
364人已围观
简介 shell 判断字符串是否存在数组中的实现示例_linux shell_
语法格式: [[ "${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[@]} 获取数组的长度。
到此这篇关于shell 判断字符串是否存在数组中的实现示例的文章就介绍到这了,更多相关shell 判断字符串在数组中内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
您可能感兴趣的文章:
相关内容
- shell之定时周期性执行脚本的方法示例_linux shell_
- shell模糊匹配与正则详解_linux shell_
- Linux Shell 如何获取参数的方法_linux shell_
- 详解NC反弹shell的几种方法_linux shell_
- Linux Shell脚本中获取本机ip地址方法_linux shell_
- Shell用sed命令删除特定行的方法_linux shell_
- Linux shell select菜单选择实现代码_linux shell_
- 工作中使用Shell实用脚本_linux shell_
- Shell中正则表达式及sed和awk常见问题_linux shell_
- shell批量创建文件并重新命名的实例代码_linux shell_
