Read files using arrays in Bash script

Read files using arrays in Bash script

I have following file with some numeric contents in it

bash-4.2$ cat /tmp/araytest.txt
1 2
3 4
5 6
7 8
9 10
11 12
13 14

If we would like save the file contents in Array. We can using following method.

 while read LINE
 do
 ARRAY+=("$LINE")
 done < <(cat /tmp/araytest.txt)

Now we can use another Loop to read it line by line for further manipulation as show below.

for i in "${ARRAY[@]}"; do
echo $i
done

Therefore full shell script should look like show below

#!/bin/bash

while read LINE
 do
 ARRAY+=("$LINE")
 done < <(cat /tmp/araytest.txt)

for i in "${ARRAY[@]}"; do
echo $i
done

Save it into file i-e testArray.sh and execute it as show below

bash-4.2$ ./testArray.sh
1 2
3 4
5 6
7 8
9 10
11 12
13 14

 

Thanks for visiting , dont forget to leave your feedback.
Regards
Raja Naveed

 

 

 

Leave a Reply

Your email address will not be published.