如何将 while read 行循环的内容输出到 bash 中的多个数组?
我读取目录的文件并将每个文件名放入数组中(搜索) 然后,我使用循环遍历数组中的每个文件名(搜索),并使用 while read 行循环打开它们,并将每一行读入另一个数组(文件计数)。我的问题是它有一个巨大的数组,有 39 行(每个文件有 13 行),我需要它是 3 个独立的数组,其中 filecount1[line1] 是第一个文件的第一行,依此类推。这是到目前为止我的代码...
typeset -A files
for file in ${SEARCH[@]}; do
while read line; do
files["$file"]+="$line"
done < "$file"
done
所以,感谢伊万提供的这个例子!但是我不确定我是否遵循如何将其放入单独的数组中,因为在这个示例中,所有数组是否仍被命名为“文件”?
I read the files of a directory and put each file name into an array (SEARCH)
Then I use a loop to go through each file name in the array (SEARCH) and open them up with a while read line loop and read each line into another array (filecount). My problem is its one huge array with 39 lines (each file has 13 lines) and I need it to be 3 seperate arrays, where
filecount1[line1] is the first line from the 1st file and so on. here is my code so far...
typeset -A files
for file in ${SEARCH[@]}; do
while read line; do
files["$file"]+="$line"
done < "$file"
done
So, Thanks Ivan for this example! However I'm not sure I follow how this puts it into a seperate array because with this example wouldnt all the arrays still be named "files"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您只是尝试将文件内容存储到数组中:
如果您想将各个行存储在数组中,您可以创建一个伪多维数组:
If you're just trying to store the file contents into an array:
If you want to store the individual lines in a array, you can create a pseudo-multi-dimensional array:
第 6 行
似乎在
$
之后缺少{
。应该是:
如果上述情况为真,那么它正在尝试将输出作为命令运行。
第 6 行是(在上面“修复”它之后):
但是
${filecount[$linenum]}
是一个值,并且您不能对一个值。应该是:
现在我很困惑,因为
{
是否实际上丢失了,或者}
是实际的拼写错误:S :P顺便说一句,bash 也支持这种语法
这应该有效:
一个小测试表明它有效
line 6 is
Seems it is missing a
{
, right after the$
.Should be:
If the above is true, then it is trying to run the output as a command.
Line 6 is (after "fixing" it above):
However
${filecount[$linenum]}
is a value and you can't have an assignment on a value.Should be:
Now I'm confused, as in whether the
{
is actually missing, or}
is the actual typo :S :Pbtw, bash supports this syntax too
This should work:
a small test shows it works