数组 – 使用Bash将文件内容提取为数组

前端之家收集整理的这篇文章主要介绍了数组 – 使用Bash将文件内容提取为数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何在Bash中逐行提取文件内容到数组中。
每行都设置为一个元素。

我试过这个:

  1. declare -a array=(`cat "file name"`)

但它没有工作,它将整行提取为[0]索引元素

您可以使用循环来读取文件的每一行并将其放入数组
  1. # Read the file in parameter and fill the array named "array"
  2. getArray() {
  3. array=() # Create array
  4. while IFS= read -r line # Read a line
  5. do
  6. array+=("$line") # Append line to the array
  7. done < "$1"
  8. }
  9.  
  10. getArray "file.txt"

如何使用你的数组:

  1. # Print the file (print each element of the array)
  2. getArray "file.txt"
  3. for e in "${array[@]}"
  4. do
  5. echo "$e"
  6. done

猜你在找的Bash相关文章