繁体   English   中英

在bash shell中使用输出文件中的数组

[英]Using array from an output file in bash shell

我需要使用数组来设置变量值,以便对输出文件进行进一步操作。

场景:

> 1. fetch the list from database 
> 2. trim the column using sed to a file named x.txt (got specific value as that is required)
> 3. this file x.txt has the below output as
10000 
20000 
30000
> 4. I need to set a variable and assign the above values to it.  
A=10000 
B=20000 
C=30000
> 5. I can invoke this variable A,B,C for further manipulations.

请让我知道如何在输出文件中定义一个分配给其变量的数组。

谢谢。

我不是在bash中使用数组的强烈支持者(如果您的代码足够复杂,需要一个数组,那么它足够复杂,需要一种更强大的语言),但是您可以:

$ unset a
$ unset i
$ declare -a a
$ while read line; do a[$((i++))]="$line"; done < x.txt

(我将交互式提示留在了适当的位置。如果要将其放在脚本中,请删除前导$ 。)

bash (从4.x版本开始)中,您可以使用mapfile命令:

mapfile -t myArray < file.txt

参见https://stackoverflow.com/a/30988704/10622916

或其他较旧bash版本的答案: https : //stackoverflow.com/a/46225812/10622916

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM