lishenghan 发表于 2018-8-27 13:26:56

记linux shell的两个小技巧:shell数组和字符串判断

  最近在使用shell写脚本的时候,想实现python中两个很简单的功能:1:判断一个字符串是否包含另一个字符串。2:怎么用实现python的列表功能。这里跟大家分享一下。
  1:判断一个字符串是否包含另一个字符串:
string="abcdefg"  
if [[ "$string" =~ "abc" ]];then
  
echo "do something.."
  
else
  
echo "nothing.."
  
fi
  以上的shell判断"abc"是否包含在字符串$string中。
  运行结果为:do something..
  2:使用shell的数组达到python的列表效果。
  定义数组:
  # test=(a b c d e f g)
  查看数组:
  # echo ${test[@]}
  a b c d e f g
  往数组中追加一个元素e:
  # test=(${test[@]} e)
  # echo ${test[@]}
  a b c d e f g e
  通过下标索引删除一个元素,shell数组的下表和python一样,是从0开始的,所以2下标代表的是第三个元素c:
  # unset test
  # echo ${test[@]}
  a b d e f g e
  数组分片,以下命令截取了test数组0-3的元素范围,即前三个元素:
  # echo ${test[@]:0:3}
  a b d
  循环访问数组:
# for element in ${test[@]}  
do
  
echo "This is $element..."
  
done
  
#result
  
This is a...
  
This is b...
  
This is d...
  
This is e...
  
This is f...
  
This is g...
  
This is e...


页: [1]
查看完整版本: 记linux shell的两个小技巧:shell数组和字符串判断