0

i'm trying to loop through an array, I have two input values and I am trying to get one value to print in val1 and the second value in val2.So I had to make a text file called test_inputs.txt which has all the inputs that I need to print

This is the text file test_inputs.txt

1,2
3,4
10,30

I already know how to put the inputs in the array but I am having trouble printing the values. So far I have this

//this reads the text file and puts it in an array
IFS=,$'\n' read -d '' -r -a array < test_inputs.txt

for i in "${array[@]}"
do 
echo "val1: ${array[$i}} and val2: ${array[$i++]}"
done

The desired output is

val1: 1 and val2: 2
val1: 3 and val2: 4
val1: 10 and val2: 30
1
  • With your loop, i takes successive elements of the array. You want to use indexes into the array. Commented Oct 12, 2022 at 6:30

2 Answers 2

1

You can use a C-style for loop:

#!/bin/bash

IFS=,$'\n' read -d '' -r -a array < test_inputs.txt
n=${#array[*]}
for ((i = 0; i < n; i += 2))
do 
    echo "val1: ${array[i]} and val2: ${array[i+1]}"
done
Sign up to request clarification or add additional context in comments.

Comments

0

I understand your question in that each line contains 2 entries, separated by a comma.

I suggest in this case to read the array line by line, instead by element:

mapfile <test_inputs.txt
for line in "${MAPFILE[@]}"
do
  echo "val1: ${line%,*} and val2: ${line#*,}"
done

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.