Jack
Jack

Reputation: 11

reading line by line from text file and output to array bash

I'm trying to read lines from a .txt and copy each line from the text to its own folder that was previously created with ARRAY

cat stores/locations.txt |while read -r LINE;do 
echo "$LINE" > county/${ARRAY[${i}]}/localstores.txt
done

when I run this it creates only 1 file in the directory county with one line of contact information for the store but what i really want it to do is to put a file in each element of the ARRAY instead of the parent folder county.

each line of data includes the following:

<storeid> <storename> <amountofEmployees> <nameofManager>

I'm super stuck and really would appreciate the help!

Upvotes: 0

Views: 2760

Answers (1)

Inian
Inian

Reputation: 85550

A simple way to do that would be as below, which creates a new file for each of the line and optionally also adds the line to an array.

 declare -A myArray()

 while IFS= read -r line # Read a line
 do
    touch  mytargetpath/"$line.txt" # Creates a new file for each of the line in the desired path
    myArray+=("$line") # Append line to the array
 done < stores/location.txt

And print array contents as:-

# Print the file (print each element of the array)

for e in "${myArray[@]}"
do
    echo "$e"
done

Upvotes: 1

Related Questions