溫馨提示×

Awk數(shù)組的遍歷技巧有哪些

awk
小樊
81
2024-10-12 06:35:56
欄目: 編程語言

在Awk中,遍歷數(shù)組是一種常見的操作。以下是一些遍歷數(shù)組的技巧:

  1. 使用for循環(huán)遍歷數(shù)組

    array=(["apple"]="fruit" ["carrot"]="vegetable")
    for item in "${array[@]}"; do
        echo "$item : ${array[$item]}"
    done
    

    輸出:

    apple : fruit
    carrot : vegetable
    
  2. 使用while循環(huán)和數(shù)組下標(biāo)遍歷數(shù)組

    array=(["apple"]="fruit" ["carrot"]="vegetable")
    i=0
    while [ $i -lt ${#array[@]} ]; do
        item=${array[$i]}
        echo "$item : ${array[$item]}"
        i=$((i+1))
    done
    

    輸出與上述for循環(huán)示例相同。

  3. 使用數(shù)組元素作為條件判斷

    array=(["apple"]="fruit" ["carrot"]="vegetable")
    for item in "${array[@]}"; do
        if [ "$item" == "apple" ]; then
            echo "Apple is a fruit."
        elif [ "$item" == "carrot" ]; then
            echo "Carrot is a vegetable."
        fi
    done
    
  4. 使用關(guān)聯(lián)數(shù)組(字典)的特性

    Awk中的關(guān)聯(lián)數(shù)組(在Bash中稱為字典)允許你使用字符串作為鍵來存儲(chǔ)和檢索值。遍歷關(guān)聯(lián)數(shù)組時(shí),可以使用asorti函數(shù)對(duì)鍵進(jìn)行排序,然后使用for循環(huán)遍歷這些鍵。

    declare -A array
    array[apple]="fruit"
    array[carrot]="vegetable"
    sorted_keys=($(asorti -k1,1 "${!array[@]}" | tr ' ' '\n'))
    for key in "${sorted_keys[@]}"; do
        echo "$key : ${array[$key]}"
    done
    

    輸出:

    apple : fruit
    carrot : vegetable
    

這些技巧可以幫助你在Awk中有效地遍歷數(shù)組并執(zhí)行相應(yīng)的操作。

0