数组处理
数组介绍及声明
变量:存储单个元素的内存空间
数组:存储多个元素的连续的内存空间,相当于多个变量的集合
数组名和索引:
索引编号从0开始,属于数值索引
索引可支持使用自定义格式,而不是数值格式,即为关联索引,关联索引需要提前使用declare声明
declare -a arrayname 声明为数组,普通数组,数值索引格式
declare -A arrayname 声明为关联数值,关联索引格式



declare -a 查看所有普通数组
declare -A 查看所有关联数组
数组赋值
arry[index]=value
arry=("value1" "value2" "value3")
read -a arry 交互式赋值


数组引用
${arryname[index]} 普通数组的索引从0开始

${arryname[*]} ${arryname[@]} 引用所有的元素

${#arryname[*]} ${#arryname[@]}数组中元素个数

删除数组
unset arryname

数组数据切片
${arryname[@]:offset:number} offer:要跳过的元素个数 number:要取出的元素个数

${arryname[@]:offset}取出跳过的元素个数所有元素
向元素中追加
ARRAY[${#ARRAY[*]}]=value 适用于普通数组 [*]代表所有元素,#所有元素个数,即可为新增加的数值索引
ARRAY[${#ARRAY[@]}]=value
转置矩阵实现
sum=0
for (( i=1;i<=3;i++ ));do
for (( j=1;j<=3;j++ ));do
let ++sum
array[$i$j]=$sum
echo -e "${array[$i$j]} \c"
done
echo
done
echo
for (( i=1;i<=3;i++ ));do
for (( j=1;j<=3;j++ ));do
echo -e "${array[$j$i]} \c"
done
echo
done

字符串处理
字符串切片
${#str}返回字符串长度
${str:offset} 同数组
${str:offset:number} 同数组

#取字符串的最右侧几个字符,取字符串的最右侧几个字符, 注意:冒号后必须有一空白字符
${var: -length}
#从最左侧跳过offset字符,一直向右取到距离最右侧lengh个字符之前的内容,即:掐头去尾
${var:offset:-length}
#先从最右侧向左取到length个字符开始,再向右取到距离最右侧offset个字符之间的内容,注意:-length前空格
${var: -length:-offset}

#其中word可以是指定的任意字符,自左而右,查找var变量所存储的字符串中,第一次出现的word, 删除字符串开头至第一次出现word字符串(含)之间的所有字符 *代表通配符
${var#*word}:
#同上,贪婪模式,不同的是,删除的是字符串开头至最后一次由word指定的字符之间的所有内容*代表通配符
${var##*word}

#其中word可以是指定的任意字符,功能:自右而左,查找var变量所存储的字符串中,第一次出现的word,删除字符串最后一个字符向左至第一次出现word字符串(含)之间的所有字符*代表通配符
${var%word*}
#同上,只不过删除字符串最右侧的字符向左至最后一次出现word字符之间的所有字符*代表通配符
${var%%word*}

查找替换
#查找var所表示的字符串中,第一次被pattern所匹配到的字符串,以substr替换之
${var/pattern/substr}
#查找var所表示的字符串中,所有能被pattern所匹配到的字符串,以substr替换之
${var//pattern/substr}
#查找var所表示的字符串中,行首被pattern所匹配到的字符串,以substr替换之
${var/#pattern/substr}
#查找var所表示的字符串中,行尾被pattern所匹配到的字符串,以substr替换之
${var/%pattern/substr}



查找删除
#删除var表示的字符串中第一次被pattern匹配到的字符串
${var/pattern}
删除var表示的字符串中所有被pattern匹配到的字符串
${var//pattern}
删除var表示的字符串中所有以pattern为行首匹配到的字符串
${var/#pattern}
删除var所表示的字符串中所有以pattern为行尾所匹配到的字符串
${var/%pattern}

字符大小写转换
#把var中的所有小写字母转换为大写
${var^^}
#把var中的所有大写字母转换为小写
${var,,}
