提取基于模式的数组中定义的字符串变量

时间:2021-03-05 20:05:57

Special parameter "$@" contains the following string variables,

特殊参数“$ @”包含以下字符串变量,

echo $@ outputs: a.bdf, b.bdf,c.nas,d.nas

echo $ @ outputs:a.bdf,b.bdf,c.nas,d.nas

I want to extract the string variables with extension 'bdf' and save it in another array. Is it possible to do so in bash?

我想用扩展名'bdf'提取字符串变量并将其保存在另一个数组中。是否有可能在bash中这样做?

3 个解决方案

#1


1  

Just iterate through it with a for loop :

只需使用for循环遍历它:

for ARG in "$@";do
    if [[ "$ARG" == *.bdf ]];then
        BDF_ARRAY+=("$ARG")    #you don't need to initialize this array before the loop in bash
    else                       #optional block, if you want to split $@ in 2 arrays
        OTHER_ARRAY+=("$ARG")  
    fi
done

echo ${BDF_ARRAY[@]}
echo ${OTHER_ARRAY[@]}

#2


0  

Using for loop

使用for循环

for i in "$@";do
    if [[ "${i##*.}" == bdf ]]; then
        ARRAY2+=("$i")
    fi
done

#3


0  

In the generic case:

在一般情况下:

#!/bin/bash

for i in "$@"; do
    case "$i" in
        *.bdf)  BDF_ARRAY+=("$i")
                ;;
        *.nas)  NAS_ARRAY+=("$i")
                ;;
    esac
done

for i in "${BDF_ARRAY[@]}"; do echo "BDF: $i"; done
for i in "${NAS_ARRAY[@]}"; do echo "NAS: $i"; done

#1


1  

Just iterate through it with a for loop :

只需使用for循环遍历它:

for ARG in "$@";do
    if [[ "$ARG" == *.bdf ]];then
        BDF_ARRAY+=("$ARG")    #you don't need to initialize this array before the loop in bash
    else                       #optional block, if you want to split $@ in 2 arrays
        OTHER_ARRAY+=("$ARG")  
    fi
done

echo ${BDF_ARRAY[@]}
echo ${OTHER_ARRAY[@]}

#2


0  

Using for loop

使用for循环

for i in "$@";do
    if [[ "${i##*.}" == bdf ]]; then
        ARRAY2+=("$i")
    fi
done

#3


0  

In the generic case:

在一般情况下:

#!/bin/bash

for i in "$@"; do
    case "$i" in
        *.bdf)  BDF_ARRAY+=("$i")
                ;;
        *.nas)  NAS_ARRAY+=("$i")
                ;;
    esac
done

for i in "${BDF_ARRAY[@]}"; do echo "BDF: $i"; done
for i in "${NAS_ARRAY[@]}"; do echo "NAS: $i"; done