Creating an array from a text file in Bash

前端 未结 6 1813
小鲜肉
小鲜肉 2020-11-22 10:25

A script takes a URL, parses it for the required fields, and redirects its output to be saved in a file, file.txt. The output is saved on a new line each time a fie

6条回答
  •  孤街浪徒
    2020-11-22 11:11

    mapfile and readarray (which are synonymous) are available in Bash version 4 and above. If you have an older version of Bash, you can use a loop to read the file into an array:

    arr=()
    while IFS= read -r line; do
      arr+=("$line")
    done < file
    

    In case the file has an incomplete (missing newline) last line, you could use this alternative:

    arr=()
    while IFS= read -r line || [[ "$line" ]]; do
      arr+=("$line")
    done < file
    

    Related:

    • Need alternative to readarray/mapfile for script on older version of Bash

提交回复
热议问题