Looping over pairs of values in bash

前端 未结 7 2049
萌比男神i
萌比男神i 2020-11-22 03:19

I have 10 text files and I want to paste each file with its pair, such that I have 5 total files.

I tried the following:

for i in 4_1 5_         


        
7条回答
  •  心在旅途
    2020-11-22 03:55

    You can use an associative array:

    animals=(dog cat mouse)
    declare -A size=(
      [dog]=big
      [cat]=medium
      [mouse]=small
    )
    declare -A sound=(
      [dog]=barks
      [cat]=purrs
      [mouse]=cheeps
    )
    for animal in "${animals[@]}"; do
      echo "$animal is ${size[$animal]} and it ${sound[$animal]}"
    done
    

    This allows you traversing pairs, triples, etc. Credits: the original idea is taken from @CharlesDuffy-s answer.

提交回复
热议问题