簡體   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