在 Bash 中从文本文件创建数组 [英] Creating an array from a text file in Bash

查看:49
本文介绍了在 Bash 中从文本文件创建数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

脚本获取一个 URL,将其解析为所需的字段,并将其输出重定向以保存在一个文件中,file.txt.每次找到字段时,输出都会保存在新行上.

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 field has been found.

A Cat
A Dog
A Mouse 
etc... 

我想获取 file.txt 并在新脚本中从中创建一个数组,其中每一行都成为数组中自己的字符串变量.到目前为止,我已经尝试过:

I want to take file.txt and create an array from it in a new script, where every line gets to be its own string variable in the array. So far I have tried:

#!/bin/bash

filename=file.txt
declare -a myArray
myArray=(`cat "$filename"`)

for (( i = 0 ; i < 9 ; i++))
do
  echo "Element [$i]: ${myArray[$i]}"
done

当我运行这个脚本时,空格会导致单词被拆分而不是

When I run this script, whitespace results in words getting split and instead of getting

Element [0]: A Cat 
Element [1]: A Dog 
etc... 

我最终得到了这个:

Element [0]: A 
Element [1]: Cat 
Element [2]: A
Element [3]: Dog 
etc... 

如何调整下面的循环,使每一行的整个字符串与数组中的每个变量一一对应?

How can I adjust the loop below such that the entire string on each line will correspond one-to-one with each variable in the array?

推荐答案

使用 mapfile 命令:

Use the mapfile command:

mapfile -t myArray < file.txt

错误是使用for——循环文件的惯用方法是:

The error is using for -- the idiomatic way to loop over lines of a file is:

while IFS= read -r line; do echo ">>$line<<"; done < file.txt

有关详细信息,请参阅 BashFAQ/005.

See BashFAQ/005 for more details.

这篇关于在 Bash 中从文本文件创建数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆