shell 中的数组操作

时间:2020-05-25
本文章向大家介绍shell 中的数组操作,主要包括shell 中的数组操作使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

shell中数组操作

1.将一个字符串按照指定分隔符转换成数组

在shell处理中,经常需要将一个字符串按照字符串中的某个分隔符转换成一个数组,从而方便处理,转换时需要环境变量IFS,指定分隔符类型:

#!/bin/bash
# test.sh
# 给定字符串,以 ; 进行分割
TEST_STR="abc;def;ghi;jkl"
# 备份之前的分隔符环境变量
OLD_IFS=$IFS
# 指定分隔符为 ;
IFS=";"
# 将字符串以 ; 分割成数组
STR_LIST=($TEST_STR)
# 恢复分隔符环境变量
IFS=$OLD_IFS

# 数组大小
echo "arry size: ${#STR_LIST[@]}"
# 数组内容
echo "arry content: ${STR_LIST[@]}"

$./test.sh
arry size: 4
arry content: abc def ghi jkl

2.判断数组中是否包含某字符串

#!/bin/bash
# test.sh
# 给定字符串,以 ; 进行分割
item_arry=($1)

# 扩展给定数组的所有索引值
for i in ${!item_arry[@]};
do
    if [ "${item_arry[$i]}" == "abc" ]; then
        echo "abc is in arry"
    fi
done

$./test.sh "abc def ghi jkl"
abc is in arry

3.判断数组内是否有重复元素

由于没有找到对应的操作,借助awk实现判断数组内是否有重复元素:

#!/bin/bash
# test.sh

# 将输入参数转为数组
item_arry=($1)

# 遍历数组元素
for i in ${item_arry[@]}; do
    echo $i
done | awk '{a[$1]++}END{for(i in a) {print a[i] ,i}}' | awk '$1>1{print $2" imte is duplicate";exit 1}'

# 判断awk的返回值,为1则有重复元素
if [ $? -ne 0 ]; then
    echo "item is duplicate"
else
    echo "item is unique"
fi

$./test.sh "abc def ghi jkl"
item is unique

$./test.sh "abcd def ghi jkl abcd"
abcd imte is duplicate
item is duplicate

原文地址:https://www.cnblogs.com/guo-yw/p/12958082.html