A script takes a URL, parses it for the required fields, and redirects its output to be saved in a file, file.txt. The output is saved on a new line each time a field has been found.
A Cat A Dog A Mouse  etc...    I want to take file.txt and create an array from it in a new script, where every line gets to be its own string variable in the array. So far I have tried: 
#!/bin/bash  filename=file.txt declare -a myArray myArray=(`cat "$filename"`)  for (( i = 0 ; i < 9 ; i++)) do   echo "Element [$i]: ${myArray[$i]}" done   When I run this script, whitespace results in words getting split and instead of getting
Element [0]: A Cat  Element [1]: A Dog  etc...    I end up getting this:
Element [0]: A  Element [1]: Cat  Element [2]: A Element [3]: Dog  etc...    How can I adjust the loop below such that the entire string on each line will correspond one-to-one with each variable in the array?
Using the tr Command to Split a String Into an Array in Bash It can be used to remove repeated characters, convert lowercase to uppercase, and replace characters. In the bash script below, the echo command pipes the string variable, $addrs , to the tr command, which splits the string variable on a delimiter, ; .
You may believe that Bash loses the capability to return function arrays. However, that is not exactly correct. It is possible to move the resultant array to a method by reference, taking cues from C/C++ developers. Such a strategy allows the method to continue to be free from references towards a global variable.
Use the mapfile command:
mapfile -t myArray < file.txt   The error is using for -- the idiomatic way to loop over lines of a file is:
while IFS= read -r line; do echo ">>$line<<"; done < file.txt   See BashFAQ/005 for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With