【问题标题】:Extract file contents into array using Bash使用 Bash 将文件内容提取到数组中
【发布时间】:2013-12-16 04:34:50
【问题描述】:

如何将文件内容逐行提取到 Bash 中的数组中。 每行都设置为一个元素。

我试过了:

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

但它不起作用,它将整行提取到[0]索引元素中

【问题讨论】:

标签: arrays bash


【解决方案1】:

对于 bash 版本 4,您可以使用:

readarray -t array < file.txt

【讨论】:

  • 这是在现代 bash 中进行的明智而有效的方式。请注意,readarraymapfile 的同义词。
  • @Håkon Hægland 我喜欢它,因为你帮助了我 :-) 非常感谢
【解决方案2】:

您可以使用循环读取文件的每一行并将其放入数组中

# Read the file in parameter and fill the array named "array"
getArray() {
    array=() # Create array
    while IFS= read -r line # Read a line
    do
        array+=("$line") # Append line to the array
    done < "$1"
}

getArray "file.txt"

如何使用你的数组:

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

【讨论】:

  • 我不知道为什么 OP 想要那个。但是,这在语法上是正确的
【解决方案3】:

这可能对你有用(Bash):

OIFS="$IFS"; IFS=$'\n'; array=($(<file)); IFS="$OIFS"

复制$IFS,将$IFS 设置为换行符,将文件插入数组并再次重置$IFS

【讨论】:

  • 这会受到路径名扩展的影响(并且会丢弃空行)——不要使用。
猜你喜欢
  • 1970-01-01
  • 2020-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多