How to insert words in 2D array with delimiters? Using BASH script -


in text file have this:

worda|wordc

wordb|wordd

i have array:

   arr=(worda|wordc wordb|wordd)    arr[0]=(worda wordc)    arr[0][0]=(worda)    arr[0][1]=(wordc)    arr[1]=(wordb wordd)    arr[1][0]=(wordb)    arr[1][1]=(wordd) 

edit: if not possible, how can have array:

   arr1=(worda wordb)    arr2=(wordc wordd) 

as mentioned bash not support true 2d arrays, can simulated using associative arrays.

something seems work ok in tests:

a=$'a|c\nb|d' echo "$a" && echo  declare -a array ifs=$'\n' read -r -d '' -a arr1 <<<"$a" #declare -p arr1 ((i=0;i<"${#arr1[@]}";i++));do   ifs="|" read -r -a arr2 <<<"${arr1[$i]}"   ((k=0;k<"${#arr2[@]}";k++));do     array[$i,$k]="${arr2[$k]}"   done done declare -p array 

output:

a|c b|d  declare -a array='([0,0]="a" [0,1]="c" [1,0]="b" [1,1]="d" )' 

so have created associative array name "array" can used in format:

echo "${array[1,0]}" #output b 

you can itterate through keys of array either classic double loops or simpler with

for key in "${!array[@]}";do echo "$key - ${array[$key]}" done 0,0 - 0,1 - c 1,0 - b 1,1 - d 

Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -