创建从BASH一个文本文件中的数组 [英] Creating an array from a text file in BASH
问题描述
这是我在计算器上的第一个问题关于bash脚本编程(希望我张贴正确)。
This is my first question on StackOverflow (hoping I'm posting correctly) regarding bash scripting.
我有一个脚本,它接受一个URL,它解析为必填字段,并重定向它的输出被保存在一个文件中, file.txt的的。每一个领域已经发现时间的输出保存在一个新行。
I have a script which 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.
file.txt example:
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
除了当我运行此脚本,空格会导致不但得不到的话越来越分裂,
Except when I run this script, whitespace will result in words getting split and instead of getting
desired output:
Element [0]: A Cat
Element [1]: A Dog
etc...
我最终得到这样的:
I end up getting this:
actual output:
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
is the command you're looking for:
mapfile -t myArray < file.txt
您的错误是使用为
- 过度的行的文件的惯用方式循环是:
Your 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
这篇关于创建从BASH一个文本文件中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!