将文件的内容分配给bash中的数组

我有一个文件,其中包含部分文件名作为换行符(或用空格分隔)。让我们以下面的例子为例:

cat file.txt
1
4
500

实际的文件名是file_1.dat, file_2.dat, file_3.dat, file_4.dat file_500.dat,等等。

我只想合并那些名称(或部分名称)存储在file.txt.

为此,我正在执行以下操作:

 ## read the file and assign to an array
 array=()
 while IFS= read -r line; do
 array+=($line)
 done < file.txt

 ## combine the contents of the files
 for file in ${array[@]}
  do
  cat "file_$file.dat"
  done > output.dat

现在在这个解决方案中,我不喜欢数组的分配,我必须为此运行一个do循环。

我试着用

 mapfile -t array < <(cat file.txt)

我也试过,

 array=( $(cat file2.txt) )

最后需要的数组是

array=(1 4 500) 

在某些答案中(在此平台中),我认为以上述方式(最后一个选项)进行操作可能有害。我想澄清一下如何处理此类任务。

我的问题是:在这种情况下,将文件内容分配到数组中的最佳(安全且快速)方法是什么?

回答

array=( $(cat file2.txt) )

不一定将每一行都放在数组中。它将分词和通配得到的每个放入数组中。

考虑这个文件

1
2 3
*

mapfile -t array < file.txt将创建元素的数组12 3*

array=( $(cat file.txt) )将创建一个包含元素12和的数组3,以及当前目录中每个文件名的元素。

使用mapfile既安全又使您更清楚地为每个元素存储一行的意图。

但是,根本不需要数组。您可以在从输入文件中提取一行时处理每个文件。

while IFS= read -r line; do
    cat "file_$line.dat"
done < file.txt > output.dat


以上是将文件的内容分配给bash中的数组的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>