Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an array from a text file in Bash

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.

file.txt

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

Desired output

Element [0]: A Cat  Element [1]: A Dog  etc...  

I end up getting this:

Actual output

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?

like image 384
user2856414 Avatar asked Jun 22 '15 19:06

user2856414


People also ask

How do I convert a string to an array in bash?

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, ; .

Can bash function return array?

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.


1 Answers

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.

like image 113
glenn jackman Avatar answered Sep 27 '22 17:09

glenn jackman