简体   繁体   English

从文本文件中逐行读取并输出到数组bash

[英]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 我正在尝试从.txt中读取行,并将文本中的每一行复制到以前使用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. 当我运行此命令时,它在目录县中仅创建1个文件,其中包含与商店的联系信息的一行信息,但我真正想要执行的操作是将文件放在ARRAY的每个元素中,而不是父文件夹县中。

each line of data includes the following: 每行数据包括以下内容:

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

I'm super stuck and really would appreciate the help! 我非常困惑,真的很感谢您的帮助!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM