如何从多个文本源的第一行创建数组?

dim*_*ech 8 bash array shell-script

我有一组文件路径,每个文件都有几行文本。我想生成一个数组,其中填充了每个文件的第一行,如下所示:

# this.txt first line is [Test this]
# another.txt first line is [Test another]
paths=(
  ./this/path/this.txt
  ./another/path/another.txt
)

for i in ${paths[@]}; do
  read -r line < $i
  lines+=$line
done
Run Code Online (Sandbox Code Playgroud)

我的数组中最多只有一个值。我似乎无法从 for 循环中获取我正在寻找的数组。我尝试了很多变体,但很难弄清楚我哪里出错了。

Mic*_*mer 11

你自找的

lines+=("$line")
Run Code Online (Sandbox Code Playgroud)

+=WORD 是字符串连接(或加法)。阿化合物分配 +=(...)追加的值到阵列。

您可能还想在此处引用所有变量扩展 -line如果该行可能包含空格,则肯定需要它,但您也可能在其他地方遇到问题。